Perl on the command line

Perl, you know perl, is not just a jewel for scripting, it ’s also a potent onliner.

The magic trick is the diamond:

perl -e ‘while (){print}’ file1

says perl “keep on as long as you read something in the standard in”, in the case of the example above, “print the line” … and each line goes in the memory but not the whole file: you have a powerful stream editor.

The ” -e” switch says to perl that what follows in the command line between the single quotations is a script and not a script file name.

But you can have it quicklier :

perl -ane ‘print’ file1

The switches “-ane” do the “while stuff” for you. It says “do a while () loop” (-n) “and split each record in the @F array” (-a), I haven’t used the array yet.
Perl has a difficulty : you can implicit everything. Some guys abuse of it in scripting, like spirits, but it’s good for an onliner.

This line will print file1. Great (in fact implicit in “print $_” ; $_ is the variable where perl puts what you do not explicit). Printing is great but let do some awkish things :

perl -ane ‘/$m[aiy]/ && print $_’

That will print the lines that contain $ma, $mi or $my, (have a look at the article from karkoma about sed), patterns in perl are like sed’s ones but larger. Take a look at the tutorial of perl for pattern or type “perldoc perlreftut” if you have installed perldoc.

Well, just let do some sedish thinks :

perl -ane ’s/

]*)>//; s/
/
/;print’ file1.html

replaces the paragraph in html( by newline () but keeps the options of the paragraph ($1, first match, here the parenthesis are not optional) in an html comment.

perl -F”:” -ane ‘/pascal/ && print $F[2]‘ /etc/passwd

will print the UID of user pascal (third field), the field separator is “:” (-F$-1òý:òý)

perl -ane ‘/$m[aiy][^ s]*/ && print “line : $. variable : $&n”‘

will print the number of line ($.) where the variables that begin with “$ma”, “$mi” o “$my” and the variables that have matched the description ($&)

bad news, you received this bad MS file with carriage return (r) and newline and you want only the newline :

perl -pi.old -ane ’s/rn$/n/;print;’ file1

and I obtain directly a file1 without carriage return and I have a backup of the original in file1.old (-pi.old)
you can have a look to a quick look at some useful perl onliners.

Leave a Reply

You must be logged in to post a comment.