Domanda

I have the following output:

vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1', 'ip=5.6.7.8, mac=00:00:00:00:00:00, bridge=eth1' ]

Sometimes, there is only one ip address. So it's:

vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1' ]

And in other cases, there are more than 2 ip addresses:

vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1', 'ip=5.6.7.8, mac=11:11:11:11:11:11, bridge=eth1', 'ip=9.1.2.3, mac=22:22:22:22:22:22, bridge=eth1' ]

Is there an easy way to get only the ip addresses? I want to store them in an array.

È stato utile?

Soluzione

This is one possibility out of many: tr -s "[,'" "\n" | grep "^ip=" | cut -d "=" -f2

Example:

echo "vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1', 'ip=5.6.7.8, mac=11:11:11:11:11:11, bridge=eth1', 'ip=9.1.2.3, mac=22:22:22:22:22:22, bridge=eth1' ]" | tr -s "[,'" "\n" | grep "^ip=" | cut -d "=" -f2

produces

1.2.3.4
5.6.7.8
9.1.2.3

Altri suggerimenti

I want to store them in an array.

you can store your searched IP addresses in array as follows.

str="vif         = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1', 'ip=5.6.7.8, mac=11:11:11:11:11:11, bridge=eth1', 'ip=9.1.2.3, mac=22:22:22:22:22:22, bridge=eth1' ]"

myarr=$(echo $str | tr -s "[,'" "\n" | awk '{for(i=1;i<=NF;i++){if($i~/ip/){sub("ip=","",$i);print $i}}}')

for i in "${myarr[@]}"
do
  printf "%s \n" $i
done

a simple and understandable solution is: (data stored in file)

cat file | grep -o "'[^']*'" | grep -o "ip=[^,]*"

output:

ip=1.2.3.4
ip=5.6.7.8
ip=9.1.2.3
ip=1.2.3.4
ip=1.2.3.4
ip=5.6.7.8

to see only addresses:

cat file | grep -o "'[^']*'" | grep -o "ip=[^,]*" | cut -d"=" -f2

output:

1.2.3.4
5.6.7.8
9.1.2.3
1.2.3.4
1.2.3.4
5.6.7.8
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top