gpt4 book ai didi

linux - 在 shell 脚本中读取第一行后读取多行输出停止

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:35:59 27 4
gpt4 key购买 nike

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

我怀疑 read -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 命令的标准输入

done < <(somecommand)

或者如果内容只是一个文件,使用文件重定向来获取它的内容

done < filename

关于linux - 在 shell 脚本中读取第一行后读取多行输出停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49047646/

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