gpt4 book ai didi

arrays - Bash 数组 : Need help with white space

转载 作者:行者123 更新时间:2023-11-29 09:24:43 25 4
gpt4 key购买 nike

我正在尝试从具有以下示例格式的文件在 bash 中创建一个数组:

data, data, interesting
data, data, more interesting

我填充数组的方式:

read -r -a DATA1 <<< $(cat $FILE | awk -F, '{ print $1 }')
read -r -a DATA2 <<< $(cat $FILE | awk -F, '{ print $2 }')
read -r -a DATA3 <<< $(cat $FILE | awk -F, '{ print $3 }')

当我检查数组 DATA3 时,有 3 个元素:

interesting
more
interesting

我需要它只显示 2 个元素,例如:

interesting
more interesting

如何保留字段 3 中的空白,以便当我从数组中调用该元素时,它看起来“更有趣”?有更好的方法来处理这个问题吗?

最佳答案

关键是将IFS(内部字段分隔符)变量与read 一起使用。

read 可以使用 -a 选项将单词直接读入数组。设置 IFS=, 它将以逗号分隔:

while read f; do
echo "$f" | (IFS=, && read -a arr && echo ${arr[2]})
done

会回显

interesting
more interesting

你也可以直接读入变量名:

IFS=, && read f1 f2 f2

编辑:我可以推荐阅读 Advanced Bash Scripting Guide .

关于arrays - Bash 数组 : Need help with white space,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2057735/

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