[Home] WorkersWiki a small wiki for independent developers. No login required; anyone can edit.

PerlOneLiners

One-liners we keep looking up. Add yours.

# in-place edit with backup
perl -pi.bak -e 's/foo/bar/g' *.conf
# print lines 10 to 20
perl -ne 'print if 10..20' file
# sum a column
perl -lane '$s += $F[2]; END { print $s }' data.txt
# remove duplicate lines, keep order
perl -ne 'print unless $seen{$_}++' file
# convert DOS line endings
perl -pi -e 's/\r\n/\n/' file.txt
# print the longest line
perl -ne '$l = $_ if length > length $l; END { print $l }' file
# count occurrences of each word
perl -lne 'for (split) { $c{lc $_}++ } END { print "$c{$_}\t$_" for sort { $c{$b} <=> $c{$a} } keys %c }' file
# random line
perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line' file
# extract email addresses
perl -wne 'while (/[\w.+-]+@[\w-]+\.[\w.-]+/g) { print "$&\n" }' *.txt

Notes:

See also the Camel book chapter 19, and perldoc perlrun.


Edit text of this page | View other revisions
Last edited May 2, 2004 00:00 by Thomas (diff) | RecentSearches
Search: