Friday, October 7, 2022

[SOLVED] How to filter the first Ip from a 5 tuple that is present in every line in Linux

Issue

I would like to filter the first IP from the given output below.

3676798  I/H      628   71.1.219.106                            10198     71.1.208.58                             20198       UDP       A
3676798  R/U      628   71.1.208.58                             20198     71.1.219.106                            10198       UDP       A
3676799  I/H      1066  71.1.57.57                              10008     71.1.57.53                              20008       UDP       A
3676799  R/U      1066  71.1.57.53                              20008     71.1.57.57                              10008       UDP       A
3676800  I/H      532   71.1.213.104                            10142     71.1.203.52                             20142       UDP       A
3676800  R/U      532   71.1.203.52                             20142     71.1.213.104                            10142       UDP       A  

Using the below command, I'm able to get all the IP's but I would like to get only the first ip from each line which has 2 IP's. There may be line which might not have IP's at all. so I would like to ignore that line.

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' <filename> 

I tried to use Awk to get it (as suggested in one of the comments) but this was unsuccessful since it prints the fourth field from any line which does not have IP's as well.

awk '{ print $4 }' file

Any pointers would be highly helpful.


Solution

To only print when the fourth field matches an IP address,

awk '$4 ~ /^[1-9][0-9]{1,2}(\.[0-9]{1,3}){3}$/{ print $4 }' file

To only print the first IP address on any line, regardless of where exactly it's found, try Perl:

perl -ne 's/.*?([0-9]{1,3}(\.[0-9]{1,3}){3}).*/$1/ and print' file

This looks quite similar to sed but the non-greedy .*? is not available in sed. If you wanted the last IP address on every line, it would be easy to do with sed.



Answered By - tripleee
Answer Checked By - Willingham (WPSolving Volunteer)