The Sysadmin Notebook  

Sitemap

Perl Oneliners

Doing things in Perl on one line

See perlrun for full details. Generally speaking, you'll want single quotes for the script part on Linux, and double quotes on Windows.

prints the lines in filename, substituting Foo with Bar

perl -p -e 's/Foo/Bar/g' filename

equivalent to 'cat filename'

perl -e 'print <>' filename

OR

perl -pe '' filename

print lines that match a pattern:

perl -ne 'print if /20:00/' filename

edits the files in-place, saving original as *.bak

perl -pi.bak -e 's/Foo/Bar/g' filename

edits the files in-place, saving original to archive/filename.bak, providing that the 'archive' directory exists.

perl -pi'archive/*.bak' -e 's/Foo/Bar/g' filename

runs two regexs on filename

perl -pi.bak -e 's/Bill Gates/Microsoft CEO/g; s/CEO/Overlord/g' filename

prints without comment lines

perl -ni.bak -e 'print unless /^\s*#/' filename

Prints file upside-down

perl -e 'print reverse <>;' filename

Prints lines in filename in alphabetical order

perl -e 'print sort <>' filename

lowercase the input

perl -ne 'print lc' filename

Display Module version numer

perl -MSome::Module -le 'print Some::Module->VERSION'

print field 2 from each line in filename. By default the field seperator is set to ' '.

 perl -lane 'print $F[1]' filename

print field 2 and 3 from each line in filename:

 perl -lane 'print $F[1..2]' filename

print field 2 and 5 from each line in filename, using 'tab' as the field separator:

 perl -F'\t' -lane 'print $F[1,4]' filename

print user description from /etc/passwd file, for first six entries

 perl -F':' -lane 'print $F[4];exit if $count++ == 5' /etc/passwd

change field 11 in a pipe-separated file

perl -F"\|" -lane "$F[10] = 'anonymouse';print join('|', @F)" lnv070409.dat

print fields 3,8,12 in a '$' seperated file if the line matches '233232'

perl -F'\$' -lane 'print $F[2], ":", $F[7], ":", $F[11] if /233232/' filename.csv