gpt4 book ai didi

linux - 使用 awk 从文件中提取信息并使用 bash 将其存储到变量中

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:04 25 4
gpt4 key购买 nike

我有一个包含以下内容的配置文件:

ip address file_location
ip address file_location
.
.
.
.

我希望我的脚本 test.sh 从这个文件中读取 IP 地址和文件位置:这是我的代码:

while read line ; do
ip=`echo $line| awk '{print $1}'`
done <test.conf

现在,当我输入 echo $ip(只是为了看看它是否有效)时,它给我一片空白。

最佳答案

这可以是一种创建 bash 数组的方法:

$ declare -A mylist
$ i=1
$ while read line; do mylist[$i]=$(echo $line | awk '{print $1}'); ((i++)); done < test.conf

然后您可以通过以下方式访问这些值:

$ for i in "${mylist[@]}"; do echo "$i"; done
ip1
ip2
ip3

或者,使用 Jonathan Leffer's very interesting approach ,您可以使用以下命令填充数组:

mylist=( $(awk '{print $1}' test.conf) )

它将像这样存储数据:

mylist=(ip1 ip2 ip3 ...)

关于linux - 使用 awk 从文件中提取信息并使用 bash 将其存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com