Grep device name and look for next value :

awkgrepsed

I have this output from a find command:

abc,10.11.13.14,def,1.2.3.4,geh,6.7.54.23

where abc,def and geh are device names and could be of any length and others are IP address belong to devices. Likeabc,10.11.13.14 for device abc. IP shall be next to comma delimiter.

How can I use sed, grep or awk to print the associated IP when I grep for a device name? In short I want the IP to be displayed next to device name.

Best Answer

I am more comfortable with awk, so I would like to present two solutions in awk.

Solution 1

$ echo abc,10.11.13.14,def,1.2.3.4,geh,6.7.54.23 | awk -F, '{for (i=1; i<NF; i+=2) if ($i == "def") print $(i+1)}'
1.2.3.4

In this case, I am looking for a machine name "def", if found, print the next column.

Solution 2

$ echo abc,10.11.13.14,def,1.2.3.4,geh,6.7.54.23 | tr , \\n | awk '/def/ {getline;print}'
1.2.3.4

In this solution, I use the tr command to convert commas to new line, search for "def" and print the line that follows. I hope these solutions work for you.

Related Question