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.
This is one possibility out of many: tr -s "[,'" "\\n" | grep "^ip=" | cut -d "=" -f2
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.