我有一个文本文件,其中包含以下信息:test.text
:
an
apple of
one's eye
我想通过执行cat test.text来使用shell脚本在数组中读取这些行。我尝试使用a=(`cat test.text`)
,但这不起作用,因为它将空间视为分隔符。我需要的值为a[0]=an
,a[1]=apple of
,a[2]=one's eye
。我不想使用IFS
。需要帮助,在此先感谢.. !!
答案 0 :(得分:2)
在bash
4或更高版本
readarray a < test.text
这将包含每个空白行的空元素,因此您可能希望首先从输入文件中删除空行。
在早期版本中,您需要手动构建阵列。
a=()
while read; do a+=("$REPLY"); done < test.text
答案 1 :(得分:1)
您拥有的各种选项之一是read
与bash一起使用。将IFS
设置为换行符,将行分隔符设置为NUL
IFS=$'\n' read -d $'\0' -a a < test.txt
答案 2 :(得分:1)
普通sh
IFS='
'
set -- $(< test.txt)
unset IFS
echo "$1"
echo "$2"
echo "$@"
bash
IFS=$'\n' a=($(< test.txt))
echo "${a[0]}"
echo "${a[1]}"
echo "${a[@]}"
我倾向于说这些是最好的解决方案,因为它们不涉及循环。
答案 3 :(得分:0)
让我们说:
cat file
an
apple of
one's eye
使用while while循环:
arr=()
while read -r l; do
[[ -n "$l" ]] && arr+=("$l")
done < file
<强> TEST 强>
set | grep arr
arr=([0]="an" [1]="apple of" [2]="one's eye")