1

the following perl one liner syntax verify if IP address in "$IP" match the IP ADDRESS in file

     perl -ne 'BEGIN{$IP=shift} print if /(^|\s)\Q$IP\E(\s|$)/;' $IP file

file have two fields

as the following example

more file


192.9.200.1  172.19.2.100
10.23.1.10   34.12.0.1
45.2.11.1    192.9.200.1
.
.
.

is it possible to define the perl syntax to match the IP that exists in the first field or the second field ? - if yes what I need to change in my syntax for that?

for example ( in case we want to match only the first field )

     perl -ne 'BEGIN{$IP=shift} print if /(^|\s)\Q$IP\E(\s|$)/;' 192.9.200.1 file

then it should to match the IP - 192.9.200.1 that exists in the first field of the line:

   "192.9.200.1  172.19.2.100"
1
  • +1 for your use of \Q and complex boundary markers. Jun 20, 2013 at 15:53

2 Answers 2

2

I would use perl's "auto-splitting" option -a and stay away from regexes

perl -lane 'BEGIN{$IP=shift} print if $F[0] eq $IP or $F[1] eq $IP' $IP file
perl -lane 'BEGIN{$IP=shift} print if grep {$_ eq $IP} @F[0,1]' $IP file

-l gives you automatic chomping and automatic newlines for print statement.

awk is simpler:

awk -v ip=$IP '$1==ip || $2==ip' file

A second reading of the question indicates you might want to match only the first column or only the 2nd column. To pass the column number as a parameter:

perl -lane '
    BEGIN {($IP,$col) = splice @ARGV,0,2}
    print if $F[$col-1] eq $IP
' $IP 2 file
awk -v ip=$IP -v col=2 '$col == ip' file

These return, given your sample data:

45.2.11.1    192.9.200.1
0

For the "there's more than one way to do it file". :-)

Another way to find the IP address either in column one or column two is to use grep.

For column 1:

grep ^192.9.200.1 file

This outputs all lines with your IP in the first column.

For column 2:

grep 192.9.200.1$ file

This outputs all lines with your IP in the last column.

I like the solution Glenn came up with using awk to see if IP is in both column 1 & 2, it's nice and readable.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .