Bag Of Tricks: A collection of nifty Perl One Liner Scripts!

Submitted by Chandrashekar Babu on August 15, 2007 - 5:57pm.
::

Work In Progress!

Perl-ish way of doing the 'cat' command:

perl -ne 'print'

Count the number of words from input stream (wc -w)

perl -lane '$c += scalar(@F); END { print $c; }'

Count the number of lines from input stream (wc -l)


perl -lne 'END { print $. }'

Count the number of characters from input stream (wc -c)

perl -ne '$c += length; END { print $c . "\n"; }'

Print the input stream with line-numbers (cat -n)

perl -lne 'print "$.\t$_"' filename.txt

Convert a DOS text file to UNIX text file (dos2unix)

perl -pie 's/\r//g' filename.txt

Convert UNIX text file to DOS text file (unix2dos)

perl -pie 's/\n/\r\n/g' filename.txt

Perl-ish substitute for 'grep' command

perl -ne '/regex-pattern/ and print'

Perl-ish substitute for 'grep -H' command

perl -ne '/Linux/ and print "$ARGV: $_"' file1.txt file2.txt ...

Perl-ish substitute for 'grep -n' command

perl -ne '/Linux/ and print "$.: $_"' file.txt

Perl-ish substitute for 'grep -v' command

perl -ne '/Linux/ or print' file.txt

Perl-ish substitute for 'grep -n' command

perl -ne '/Linux/ and print "$.: $_"' file.txt

Extracting columns/fields from input stream (cut command)

perl -lne '@A = split /:/; print $A[0]'

Translate CSV format file to HTML table data

perl -lne 'BEGIN { print "<table>" }
print "<tr>";
print "<td>$_</td>" foreach(split /;/);
print "</tr>";
END { print "</table>" }'

Extract URLs from a (HTML) file

perl -nle 'print $1 while /\<a\b[^\>\"]*?\bhref\s*=\s*[\"]?([^\>\"]*)/gi' index.html