Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Grabbing the nth and mth delimited words from each line in a file

Because of the more tedious way of adding hosts to be monitored in Nagios (it requires defining a host object, as opposed to the previous program which only required the IP and hostname), I figured it'd be best to automate this, and it'd be a great time to learn Perl, because all I know at the moment is C/C++ and Java.

The file I read from looks like this:

xxx.xxx.xxx.xxx hostname #comments. i.dont. care. about

All I want are the first 2 bunches of characters. These are obviously space delimited, but for the sake of generality, it might as well be anything. To make it more general, why not the first and third, or fourth and tenth? Surely there must be some regex action involved, but I'll leave that tag off for the moment, just in case.

like image 808
ray Avatar asked Oct 01 '08 02:10

ray


2 Answers

The one-liner is great, if you're not writing more Perl to handle the result.

More generally though, in the context of a larger Perl program, you would either write a custom regular expression, for example:

if($line =~ m/(\S+)\s+(\S+)/) {
     $ip = $1;
     $hostname = $2;
}

... or you would use the split operator.

my @arr = split(/ /, $line);
$ip = $arr[0];
$hostname = $arr[1];

Either way, add logic to check for invalid input.

like image 97
slim Avatar answered Sep 20 '22 13:09

slim


Let's turn this into code golf! Based on David's excellent answer, here's mine:

perl -ane 'print "@F[0,1]\n";'

Edit: A real golf submission would look more like this (shaving off five strokes):

perl -ape '$_="@F[0,1]
"'

but that's less readable for this question's purposes. :-P

like image 21
Chris Jester-Young Avatar answered Sep 18 '22 13:09

Chris Jester-Young