Perl One Liners

I think Perl one liners are still super useful (even Kubernetes people like them to do their jobs :-). They are small Perl programs that are run directly from a command line (ex. on Unix/Linux, Cygwin). For a deeper dive see Famous Perl One-Liners Explained. If you want a book have a look at Minimal Perl for UNIX and Linux People.

perl command line switches

See perlrun for more.

Unix tools replacements

grep replacement

Find lines containing <regex>:

perl -lne 'print if /<regex>/' aFile

Find DNS resource records of type A:

find /etc/bind -type f | xargs perl -ne '/\s+A\s+/ and print "$ARGV: $_"'

sed replacement

Emit the transformed passwd file to STDOUT:

perl -pe 's#/bin/sh$#/bin/bash#' /etc/passwd

In-place editing with backups:

perl -i.bak -pe 's/colour/color/g' *.txt

awk replacement

Switch columns:

$ cat birthdays.txt
03/30/45 Eric Clapton
11/27/42 Jimi Hendrix
06/24/44 Jeff Beck
$ perl -lane 'print "@F[1,0]"' birthdays.txt

Leave out the first column:

history | perl -anE 'say join " ", @F[1 .. $#F]' | sort | uniq

dos2unix replacement

Convert DOS files to Unix files:

perl -i -pe 's/\r//' <file1> <file2> ...   # dos-to-unix
perl -i -pe 's/$/\r/' <file1> <file2> ...  # unix-to-dos


Total size of found files (using the Eskimo Greeting Operator as suggested by PerlMonks):

find /opt/splunk/syslog/ -iname "*log*" -type f -mtime +30 | \
perl -lne '$sum += (stat)[7]}{print $sum'

Remove comments and compress all consecutive blank lines into one (more):

cat /etc/ssh/sshd_config | perl -lne '!/^#/ and print' | perl -00 -pe ''

Create HTML anchor element:

perl -le 'print "<a href=\"$ARGV[1]\">$ARGV[0]</a>"' 'perldoc'


Find big palindromes:

perl -lne 'print if $_ eq reverse and length >= 5' /usr/share/dict/words

Print a file system tree on UNIX like systems (source):

ls -R | perl -ne'if(s/:$//){s{[^/]*/}{--}g;s/^-/\t|/;print}'

Greet user (stolen from Utilitarian) (-:

perl -E 'say "Good ".qw(night morning afternoon evening)[(localtime)[2]/6].", $ENV{USER}"'
comments powered by Disqus