Reputation: 1133
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.
Upvotes: 1
Views: 2051
Reputation: 25865
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
Upvotes: 1
Reputation: 5414
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
Upvotes: 0
Reputation: 21469
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
Upvotes: 2