Call: (480) 382-8464

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

-e
Allows it to be a one-liner
-l
print a newline in addition to whatever you print
-n
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 *

Main Offers/Services

Hosting and website related services offered by Digital Crunch:



Managed VPS Hosting

Server Updates, Module/Software Installs, Firewall, Security, Hosting Management, Wordpress - let us manage it for you

Hosted Email

Setup and Maintain Business Class, Secure Email Hosting including spam protection and 25GB of storage space

Linux Consulting

Server Updates, Module/Software Installs, Firewall, Security, Hosting, Wordpress and Apps, anything related to Linux

Email Marketing Services

We broadcast your content to your list, capture leads for you, follow up on schedules, make more sales for you

Website Maintenance

Content updates, menu changes, graphics changes, adding content, getting links, building traffic, building sales funnels

Hosting Tutorials

Tutorials we've written for other customers that like to get their hands dirty and learn about hosting