PerlFastLane

Note: You are viewing an old revision of this page. View the current version.

Goodbye awk, I've finally come to understand the awesomeness of the perl -lane method of running perl oneliner command scripts.

Use case: take output from a script, find line you are interested in, output parts of it, with hostname prepended.

Here's the script output:

$ /usr/sbin/db_update -check
db_update: Version available from dist:  1.15.130 (built: Mon Jan 31 02:32:12 2011)
db_update: Installed database version:   1.15.130 (built: Mon Jan 31 02:32:12 2011)
db_update: Installed database status:    OK (Matches dist version)
db_update: Installed database age:       30 days since db was built

I want to know the installed database version, in this format:

bargle.example.com: 1.15.30

And here's a perl oneliner to do it:

/home/sbin/db_update -check | perl -MSys::Hostname -lane 'print hostname.": ".$F[4] if /Installed database version/'

The key point here is use of -a to autosplit the input line into array @F. You can then use $F[4] exactly like you do in awk '{ print $4 }'. This whole thing is generally a replacement for the standard awk 'find a line and output part of it' idiom: awk '/Installed database version/ '{ print $4 }'. The advantage here is the integration of additional data (like the hostname) is quite simple. I realize that awk programmers out there can probably do this in an equally simple way. If so, please give me your solution in the comments!

http://blog.ksplice.com/2010/05/top-10-perl-one-liner-tricks/

http://www.catonmat.net/blog/perl-one-liners-explained-part-two



Our Founder
ToolboxClick to hide/show