5

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?

Wildcard
  • 36,499

2 Answers2

6

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 
$ 
Wildcard
  • 36,499
0
myvariable=$(yourmysterycommand |
               sed -e 's/id1=//;
                       s/id5=.*//;
                       s/"//g;
                       s/id.=/./g;
                       s/[[:blank:]]\+//g' |
               paste -sd' ')

That's a one-liner, but reformatted with extra newlines and indentation for readability.

$ echo "$myvariable"
172.17.136.5 172.17.128.2 172.17.128.4 172.17.128.6

The sed command removes the string id1=, then removes id5= and everything following, then removes all double-quote characters ("), changes all occurences of id.= to a literal ., and finally removes all blank characters (spaces and/or tabs) from the line.

The paste command joins the lines with a space character as delimiter.


BTW, a better solution would be to fix whatever program is printing IP addresses in such a useless and dumb format. An octet in an IP address is not any kind of an "id".

cas
  • 78,579