Perl Oneliners

Generate a random character password

  perl -le 'print map { ("a".."z")[rand 26] } 1..8'

Create a string of specific length

  perl -le 'print "a"x50'

Create a repeated list of elements

  perl -le '@list = (1,2)x20; print "@list"'

Create a string from an array

  perl -le "@stuff = ("hello", 0..9, "world"); print join '-', @stuff"

Find the numeric values for characters in the string

  perl -le 'print join ", ", map { ord } split //, "hello world"'

Convert a list of numeric ASCII values into a string

  perl -le '@ascii = (99, 111, 100, 105, 110, 103); print pack("C*", @ascii)'
  perl -le '@ascii = (99, 111, 100, 105, 110, 103); print map { chr } @ascii'

Generate an array with odd numbers from 1 to 100

  perl -le '@odd = grep {$_ % 2 == 1} 1..100; print "@odd"'

Generate an array with even numbers from 1 to 100

  perl -le '@even = grep {$_ % 2 == 0} 1..100; print "@even"'

Find the length of the string

  perl -le 'print length "one-liners are great"'

Find the number of elements in an array

  perl -le '@array = ("a".."z"); print scalar @array'
  perl -le '@array = ("a".."z"); print $#array + 1'

Perl one-liner to get the current week number

  perl -e 'use Date::Calc qw(Today Week_Number); $weekn = Week_Number(Today); print "$weekn\n"'

Pick a random line from a file

  perl -e 'rand($.) < 1 && ($line = $_) while <>;'

Print a list of standard error codes and descriptions.

  perl -le 'print $!+0, "\t", $!++ for 0..127'

Rearrange words from a file

  perl -lane 'print "$F[0]:$F[1]:$F[2]"' myfile

Recursive Search and Replace

  perl -pi -e's/WHAT TO FIND/WHAT TO REPLACE IT WITH/g' $(grep -Rl WHAT TO FIND /DIR/*)

Remove duplicate rows of an un-sorted file based on a single column

  perl -ane 'print unless $x{$F[0]}++' infile > outfile

Replace all environment variable references in files with environemnt variable values

  perl -p -e 's/\$(\w+)/$ENV{$1}/g;' FILES...

Show full path followed by a command

  perl -le 'chomp($w=$(which $ARGV[0]));$_=$(file $w);while(/link\b/){chomp($_=(split/''/,$_)[1]);chop$_;$w.=" -> $_";$_=''file $_`;}print "\n$w";' COMMAND_NAME

Show which include directories your installation of Perl is using.

  perl -le 'print join $/, @INC'

Sum column 1

  perl -alne 'END{print $a} $a+=$F[0]' <inputfile

Check if a number is a prime

  perl -lne '(1x$_) !~ /^1?$|^(11+?)\1+$/ && print "$_ is prime"'

Print the sum of all the fields on a line

  perl -MList::Util=sum -alne 'print sum @F'

Print the sum of all the fields on all lines

  perl -MList::Util=sum -alne 'push @S,@F; END { print sum @S }'
  perl -MList::Util=sum -alne '$s += sum @F; END { print $s }'

Shuffle all fields on a line

  perl -MList::Util=shuffle -alne 'print "@{[shuffle @F]}"'
  perl -MList::Util=shuffle -alne 'print join " ", shuffle @F'

Find the minimum element on a line

  perl -MList::Util=min -alne 'print min @F'

Find the minimum element over all the lines

  perl -MList::Util=min -alne '@M = (@M, @F); END { print min @M }'
  perl -MList::Util=min -alne '$min = min @F; $rmin = $min unless defined $rmin && $min > $rmin; END { print $rmin }'

Find the maximum element on a line

  perl -MList::Util=max -alne 'print max @F'

Find the maximum element over all the lines

  perl -MList::Util=max -alne '@M = (@M, @F); END { print max @M }'

Replace each field with its absolute value

  perl -alne 'print "@{[map { abs } @F]}"'

Find the total number of fields (words) on each line

  perl -alne 'print scalar @F'

Print the total number of fields (words) on each line followed by the line

  perl -alne 'print scalar @F, " $_"'

Find the total number of fields (words) on all lines

  perl -alne '$t += @F; END { print $t}'

Print the total number of fields that match a pattern

  perl -alne 'map { /regex/ && $t++ } @F; END { print $t }'
  perl -alne '$t += /regex/ for @F; END { print $t }'
  perl -alne '$t += grep /regex/, @F; END { print $t }'

Print the total number of lines that match a pattern

  perl -lne '/regex/ && $t++; END { print $t }'

Generate 10 random numbers between 5 and 15 (excluding 15)

  perl -le '$n=10; $min=5; $max=15; $, = " "; print map { int(rand($max-$min))+$min } 1..$n'

Convert an IP address to unsigned integer

perl -le '$i=3; $u += ($_<<8*$i--) for "127.0.0.1" =~ /(\d+)/g; print $u'
perl -le '$ip="127.0.0.1"; $ip =~ s/(\d+)\.?/sprintf("%02x", $1)/ge; print hex($ip)'
perl -le 'print unpack("N", 127.0.0.1)'
perl -MSocket -le 'print unpack("N", inet_aton("127.0.0.1"))'

Convert an unsigned integer to an IP address

  perl -MSocket -le 'print inet_ntoa(pack("N", 2130706433))'
  perl -le '$ip = 2130706433; print join ".", map { (($ip>>8*($_))&0xFF) } reverse 0..3'
  perl -le '$ip = 2130706433; $, = "."; print map { (($ip>>8*($_))&0xFF) } reverse 0..3'

Convert a decimal number to hex using @hex lookup table

  perl -le '$num = 255; @hex = (0..9, "a".."f"); while ($num) { $s = $hex[($num%16)&15].$s; $num = int $num/16 } print $s'
  perl -le '$hex = sprintf("%x", 255); print $hex'
  perl -le '$num = "ff"; print hex $num'

N-space a file

  perl -pe '$_.="\n"x7'

Remove all blank lines

  perl -ne 'print unless /^$/'
  perl -lne 'print if length'
  perl -ne 'print if /\S/'

Remove all consecutive blank lines, leaving just one

  perl -00 -pe ''
  perl -00pe0

Number only non-empty lines in a file

  perl -pe '$_ = ++$a." $_" if /./'

Number and print only non-empty lines in a file (drop empty lines)

  perl -ne 'print ++$a." $_" if /./'

Print the number of lines in a file that match a pattern (emulate grep

  perl -lne '$a++ if /regex/; END {print $a+0}'
  perl -nE '$a++ if /regex/; END {say $a+0}'

Reverse a file

  perl -e'@f=<>;print reverse@f' file

ROT 13 a file

  perl -lpe 'y/A-Za-z/N-ZA-Mn-za-m/' file

Base64 encode a string

  perl -MMIME::Base64 -e 'print encode_base64("string")'
  perl -MMIME::Base64 -0777 -ne 'print encode_base64($_)' file

Base64 decode a string

  perl -MMIME::Base64 -le 'print decode_base64("base64string")'
  perl -MMIME::Base64 -ne 'print decode_base64($_)' file

URL-escape a string

  perl -MURI::Escape -le 'print uri_escape($string)'

URL-unescape a string

  perl -MURI::Escape -le 'print uri_unescape($string)'

HTML-encode a string

  perl -MHTML::Entities -le 'print encode_entities($string)'

HTML-decode a string

  perl -MHTML::Entities -le 'print decode_entities($string)'

Convert all text to uppercase

  perl -nle 'print uc'
  perl -ple '$_=uc'
  perl -nle 'print "\U$_"'

Convert all text to lowercase

  perl -nle 'print lc'
  perl -ple '$_=lc'
  perl -nle 'print "\L$_"'

Uppercase only the first word of each line

  perl -nle 'print ucfirst lc'
  perl -nle 'print "\u\L$_"'

Invert the letter case

  perl -ple 'y/A-Za-z/a-zA-Z/'

Camel case each line

  perl -ple 's/(\w+)/\u$1/g'
  perl -ple "s/(?<!['])(\w+)/\u\1/g"

Strip leading whitespace (spaces, tabs) from the beginning of each line

  perl -ple 's/^[ \t]+//'
  perl -ple 's/^\s+//'

Strip trailing whitespace (space, tabs) from the end of each line

  perl -ple 's/[ \t]+$//'

Strip whitespace from the beginning and end of each line

  perl -ple 's/^[ \t]+|[ \t]+$//g'

Convert UNIX newlines to DOS/Windows newlines

  perl -pe 's|\n|\r\n|'

Convert DOS/Windows newlines to UNIX newlines

  perl -pe 's|\r\n|\n|'

Convert UNIX newlines to Mac newlines

  perl -pe 's|\n|\r|'

Substitute (find and replace) “foo” with “bar” on each line

  perl -pe 's/foo/bar/'

Substitute (find and replace) all “foo”s with “bar” on each line

  perl -pe 's/foo/bar/g'

Substitute (find and replace) “foo” with “bar” on lines that match “baz”

  perl -pe '/baz/ && s/foo/bar/'

Binary patch a file (find and replace a given array of bytes as hex numbers)

  perl -pi -e 's/\x89\xD8\x48\x8B/\x90\x90\x48\x8B/g' file

print the first line of a file (emulate head -1)

  perl -ne 'print; exit'

print the first 10 lines of a file (emulate head -10)

  perl -ne 'print if $. <= 10'
  perl -ne '$. <= 10 && print'
  perl -ne 'print if 1..10'

print the last line of a file (emulate tail -1)

  perl -ne '$last = $_; end { print $last }'
  perl -ne 'print if eof'

print the last 10 lines of a file (emulate tail -10)

  perl -ne 'push @a, $_; @a = @a[@a-10..$#a]; end { print @a }'

print only lines that match a regular expression

  perl -ne '/regex/ && print'

print only lines that do not match a regular expression

  perl -ne '!/regex/ && print'

print the line before a line that matches a regular expression

  perl -ne '/regex/ && $last && print $last; $last = $_'

print the line after a line that matches a regular expression

  perl -ne 'if ($p) { print; $p = 0 } $p++ if /regex/'

print all lines between two regexes (including lines that match regex)

  perl -ne 'print if /regex1/../regex2/'

print all lines from line 17 to line 30

  perl -ne 'print if $. >= 17 && $. <= 30'
  perl -ne 'print if int($.) ~~ (17..30)'
  perl -ne 'print if grep { $_ == $. } 17..30'

print all lines that contain only characters

  perl -ne 'print if /^[[:alpha:]]+$/'

print all unique lines

  perl -ne 'print unless $a{$_}++'

print the first field (word) of every line (emulate cut -f 1 -d ’ ’)

  perl -alne 'print $f[0]'