Perl One Liners

Perl One Liners can help you quickly edit files, strip lines, and perform other common admin tasks. Here is a small collection of my perl one liners that I’ve used recently.

Perl One Liner Basics

  • enclose program in single quotes to avoid shell expansion
  • you don’t need the final semicolon
  • no strict, no warnings, no tests (unless specified)

Perl One Liner Flags

Allows it to be a one-liner
print a newline in addition to whatever you print
automatically wrap the one-liner in a loop instead of saying perl -e ‘while (<>) { print $_ }’ *.txt, you can say: perl -ne ‘print $_’ *.txt
-i or -i.bak
make changes directly to the file isntead of STDOUT or saves to .bak instead of clobbering your good file

Perl One Liners

The following perl one liner examples have been useful in some way to me. I hope they are useful to you too.

remove blank lines:
perl -ni.bak -e 's/^\s*$//' somefile
remove comment lines:
perl -ni.bak -e 's/^#.*$//' somefile
install some::module
perl -MCPAN -e 'install Some::Module'
Search and Replace:
perl -pi -e 's/change/to this/g' somefile
Find Repeated Lines:
perl -ne 'print if $x{$_}++' somefile
Generate an 8 Letter (Weak) Password:
perl -le 'print map { (a..z)[rand 26] } 1..8'
Find Palindromes:
perl -lne 'print if $_ eq reverse' /usr/dict/words
Strip Most HTML:
cat index.htm | perl -ne 's/\<[^<]*\>//g ;print $_'
Convert File to Lowercase:
perl -ne 'tr/A-Z/a-z/; print' somefile
Add Line to Beginning of File:
perl -0777 -i -ne 'print "first line here\n$_"; somefile
Find href tags:
perl -nle 'print $1 while /\<a\b[^\>"]*?\bhref=\"?([^\>"]*)/g' somefile
Remove Duplicate Lines
perl -e '$u=0;while(<>){if(!($s{$_}++)){print $_;$u++}} warn "$u unique of $. total lines.\n"' infile outfile
Available DBI Drivers
perl -e "use DBI; print map qq~$_\n~, DBI->available_drivers;";

Perl DBI one liner available drivers

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.