Bash Command Line – Compose String of IPs

bashshell-scripttext processing

I have a command that returns the following:

 id1="172" id2="17" id3="136" id4="5" id5="0" />
 id1="172" id2="17" id3="128" id4="2" id5="0" />
 id1="172" id2="17" id3="128" id4="4" id5="0" />
 id1="172" id2="17" id3="128" id4="6" id5="0" />

The first four IDs combined represent an IP address (e.g. 172.17.136.5 for the first line).

I would like to pipe the above to a parsing command which will output a single string with all the IP addresses separated by spaces.

For the above example:

myVariable="172.17.136.5 172.17.128.2 172.17.128.4 172.17.128.6"

How can I do this?

Best Answer

You can do this with an awk command most easily:

your-command | awk -F\" -v OFS=. -v ORS=' ' '{print $2, $4, $6, $8}'

To set it as a variable, use command substitution:

myVariable="$(your-command | awk -F\" -v OFS=. -v ORS=' ' '{print $2, $4, $6, $8}')"

-F sets the input field separator (which is by default any whitespace) to a custom value; in this case a double quote (").

-v allows you to set awk variables.

OFS is the output field separator, by default a single space. We set it to a period.

ORS is the output record separator, by default a newline. We set it to a space.

Then we print the 2nd, 4th, 6th and 8th fields for each line of the input.


Sample output:

$ cat temp
 id1="172" id2="17" id3="136" id4="5" id5="0" />
 id1="172" id2="17" id3="128" id4="2" id5="0" />
 id1="172" id2="17" id3="128" id4="4" id5="0" />
 id1="172" id2="17" id3="128" id4="6" id5="0" />
$ myVariable="$(cat temp | awk -F\" -v OFS=. -v ORS=' ' '{print $2, $4, $6, $8}')"
$ echo "$myVariable" 
172.17.136.5 172.17.128.2 172.17.128.4 172.17.128.6 
$ 
Related Question