繁体   English   中英

Bash脚本从文件读取并将信息保存在数组中?

[英]Bash script to read from a file and save the information in an array?

我想从写有主机IP的文件中读取并将其保存在阵列中。 到目前为止,我已经尝试过了:

Host=`cat /home/hp3385/Desktop/config | egrep '^Host' | awk '{print $2}'`

但是我不认为它将信息保存在一个数组中。 变量“主机”的类型是什么? 如果不是数组,如何将其转换为一个数组? 这是来自文件/home/hp3385/Desktop/config的样本数据:

############# Server1 #################
Host 8.8.8.8
Hostname google

############# Server2 ################
Host 8.8.4.4
Hostname google

预期输出为: a=($'8.8.8.8' $'8.8.4.4')

你可以试试这个

myarray=()
while read -r line; do
  if echo "$line" | grep -q 'Host '; then
     myarray+=($(echo "$line" | awk '/^Host/ {print $2}'))
  fi
done < /home/hp3385/Desktop/config 

声明一个数组:

ARRAY=(0 1 2 3 4 5)

因此,您的数组可以这样声明:

HOSTS=($(awk '/^Host/ {print $2}' YOUR_FILE))

如果您想知道数组中的值数量:

echo ${#HOSTS[*]}

要获得数组中所有值的输出(贷记为Triplee ):

printf '%s\n' "${HOSTS[@]}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM