我有以下输出:
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' ]
有时,只有一个IP地址。所以它是:
vif = [ 'ip=1.2.3.4, mac=00:00:00:00:00:00, bridge=eth1' ]
在其他情况下,有超过2个IP地址:
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' ]
是否有一种简单的方法来获取IP地址?我想将它们存储在数组中。
答案 0 :(得分:2)
这是许多人的一种可能性:tr -s "[,'" "\n" | grep "^ip=" | cut -d "=" -f2
示例:
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
产生
1.2.3.4
5.6.7.8
9.1.2.3
答案 1 :(得分:1)
I want to store them in an array.
您可以按如下方式将搜索到的IP地址存储在数组中。
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
答案 2 :(得分:0)
一个简单易懂的解决方案是:(数据存储在file
)
cat file | grep -o "'[^']*'" | grep -o "ip=[^,]*"
输出:
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
仅查看地址:
cat file | grep -o "'[^']*'" | grep -o "ip=[^,]*" | cut -d"=" -f2
输出:
1.2.3.4
5.6.7.8
9.1.2.3
1.2.3.4
1.2.3.4
5.6.7.8