将输出重定向到一个bash数组 [英] Redirect output to a bash array
问题描述
我有一个包含字符串的文件
I have a file containing the string
ipAddress=10.78.90.137;10.78.90.149
我想打这两个IP地址在bash阵列。为了达到这个我试过如下:
I'd like to place these two IP addresses in a bash array. To achieve that I tried the following:
n=$(grep -i ipaddress /opt/ipfile | cut -d'=' -f2 | tr ';' ' ')
这导致在正常的提取值,但由于某些原因所述阵列的大小被返回为1,我注意到,这两个值被确定为在阵列中的第一个元素。这就是
This results in extracting the values alright but for some reason the size of the array is returned as 1 and I notice that both the values are identified as the first element in the array. That is
echo ${n[0]}
返回
10.78.90.137 10.78.90.149
我该如何解决这个问题?
How do I fix this?
感谢您的帮助!
推荐答案
你真的需要一个数组
庆典
$ 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"
如果你想放入数组
$ a=( $@ )
$ echo ${a[0]}
10.78.90.137
$ echo ${a[1]}
10.78.90.149
@OP,关于你的方法:设置为IFS空间
@OP, regarding your method: set your IFS to a space
$ 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
此外,也没有必要使用这样的工具。你可以只用awk,或者干脆使用bash shell
Also, there is no need to use so many tools. you can just use awk, or simply the 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[@]}
输出
$ 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
gawk的
$ 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
这篇关于将输出重定向到一个bash数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!