Wednesday, March 26, 2008

Perl one liners

Perl one liners is a pretty cool thing.. OK for some one who is not familiar with awk or sed ?

Whatever, I believed Perl one liner is what I need is for a simple task at hand. I have a log file where the fields are separated by spaces. I wanted to extract a field from the file.

I started by skimming through http://search.cpan.org/dist/perl/pod/perlrun.pod. I figured out the options I needed are:

-a : turns on autosplit mode when used with a -n or -p. An implicit split command to the @F array is done as the first thing inside the implicit while loop produced by the -n or -p.

-n: causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:
  LINE:
while (<>) {
... # your program goes here
}
Note that the lines are not printed by default.
-e: may be used to enter one line of program. If -e is given, Perl will not look for a filename in the argument list. Multiple -e commands may be given to build up a multi-line script. Make sure to use semicolons where you would in a normal program.

And there were a ton of examples of the Perl one-liners on the above URL too.. so my Perl one liner came up as below:

perl -ane 'print $F[20], $F[23], "\n" if defined $F[20];' logfile.log