IFS="\n"
for line in $text; do
read -a array <<< $line
echo ${array[0]}
done
$ text的内容:
123 456
abc def
hello world
预期结果 :
123
456
abc
def
hello
world
实际结果:
123
我怀疑读取-a是停止for循环的那个!我怎么能解决这个问题?
您不需要将IFS
修改为新的行字符,然后使用for
循环遍历行。只需使用read
命令从字符串中读取即可。
您可以使用单独的占位符变量来存储行中的每一行,而不是将整行读取到数组中。下面假设shell是非POSIX shell,如bash
,因为原生POSIX sh
shell不支持数组。
#!/usr/bin/env bash
text='123 456
abc def
hello world'
declare -a arrayStorage
while read -r row1 row2; do
arrayStorage+=( "$row1" )
arrayStorage+=( "$row2" )
done <<< "$text"
并使用下面的printf
打印数组应该根据需要生成输出。
printf '%s\n' "${arrayStorage[@]}"
如果相反,text
是正在运行的命令的输出,请在命令上使用进程替换语法,如下所示。这样,命令的输出连接到read
命令的stdin
done < <(somecommand)
或者,如果内容只是一个文件,请使用文件重定向来覆盖其内容
done < filename
给零(0)里面请给变量名
for line in $text; do
read -a array <<< $line
echo ${array[index]}
done