home / blog

Command line perl

I find this much more useful than sed.

Example 1: Filter/regex. Print numbers from matching lines.

foo 12 
bar 23
other
baz 34

-e is script mode. -n loops over your input automatically.

# -n option does the while loop for you
horse:~ adam$ perl -ne 'print "$1\n" if /(\d+)/' foo.txt
12
23
34

Without the -n option you’d have to add your own while loop.

perl -e 'while(<>) { print "$1\n" if /(\d+)/ }' foo.txt
12
23
34

Example 2: Modify. Wrap all numbers. -p loops around and prints the value of the substitution – much like sed

perl -pe 's/(\d+)/#$1#/' foo.txt
foo #12# 
bar #23#
other
baz #34#
This entry was posted in geek and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.