在shell脚本中的第一行之后读取后,读取多行输出会停止

问题描述 投票:1回答:2
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循环的那个!我怎么能解决这个问题?

linux shell
2个回答
1
投票

您不需要将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
投票

给零(0)里面请给变量名

for line in $text; do 
    read -a array <<< $line
    echo ${array[index]}
done
© www.soinside.com 2019 - 2024. All rights reserved.