cal*_*shy 19 bash shell redirect
我有一个包含字符串的文件
ipAddress=10.78.90.137;10.78.90.149
Run Code Online (Sandbox Code Playgroud)
我想将这两个IP地址放在一个bash数组中.为此,我尝试了以下方法:
n=$(grep -i ipaddress /opt/ipfile | cut -d'=' -f2 | tr ';' ' ')
Run Code Online (Sandbox Code Playgroud)
这导致提取值正常,但由于某种原因,数组的大小返回为1,我注意到这两个值都被标识为数组中的第一个元素.那是
echo ${n[0]}
Run Code Online (Sandbox Code Playgroud)
回报
10.78.90.137 10.78.90.149
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
谢谢您的帮助!
gho*_*g74 20
你真的需要一个阵列吗?
庆典
$ ipAddress="10.78.90.137;10.78.90.149"
$ IFS=";"
$ set -- $ipAddress
$ echo $1
10.78.90.137
$ echo $2
10.78.90.149
$ unset IFS
$ echo $@ #this is "array"
Run Code Online (Sandbox Code Playgroud)
如果你想放入数组
$ a=( $@ )
$ echo ${a[0]}
10.78.90.137
$ echo ${a[1]}
10.78.90.149
Run Code Online (Sandbox Code Playgroud)
@OP,关于你的方法:将你的IFS设置为空格
$ IFS=" "
$ n=( $(grep -i ipaddress file | cut -d'=' -f2 | tr ';' ' ' | sed 's/"//g' ) )
$ echo ${n[1]}
10.78.90.149
$ echo ${n[0]}
10.78.90.137
$ unset IFS
Run Code Online (Sandbox Code Playgroud)
而且,不需要使用这么多工具.你可以使用awk,或简单地使用bash shell
#!/bin/bash
declare -a arr
while IFS="=" read -r caption addresses
do
case "$caption" in
ipAddress*)
addresses=${addresses//[\"]/}
arr=( ${arr[@]} ${addresses//;/ } )
esac
done < "file"
echo ${arr[@]}
Run Code Online (Sandbox Code Playgroud)
产量
$ more file
foo
bar
ipAddress="10.78.91.138;10.78.90.150;10.77.1.101"
foo1
ipAddress="10.78.90.137;10.78.90.149"
bar1
$./shell.sh
10.78.91.138 10.78.90.150 10.77.1.101 10.78.90.137 10.78.90.149
Run Code Online (Sandbox Code Playgroud)
呆子
$ n=( $(gawk -F"=" '/ipAddress/{gsub(/\"/,"",$2);gsub(/;/," ",$2) ;printf $2" "}' file) )
$ echo ${n[@]}
10.78.91.138 10.78.90.150 10.77.1.101 10.78.90.137 10.78.90.149
Run Code Online (Sandbox Code Playgroud)
这个工作:
n=(`grep -i ipaddress filename | cut -d"=" -f2 | tr ';' ' '`)
Run Code Online (Sandbox Code Playgroud)
编辑:(根据丹尼斯的改进,可嵌套版本)
n=($(grep -i ipaddress filename | cut -d"=" -f2 | tr ';' ' '))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35611 次 |
| 最近记录: |