bash 如何在bash中逐行将命令输出转换为数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8768420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert command output to an array line by line in bash?
提问by Thomas Jung
I'm trying to convert the output of a command like echo -e "a b\nc\nd e"to an array.
我正在尝试将命令的输出转换为echo -e "a b\nc\nd e"数组。
X=( $(echo -e "a b\nc\nd e") )
Splits the input for every new line and whitespace character:
拆分每个新行和空白字符的输入:
$ echo ${#X[@]}
> 5
for i in ${X[@]} ; do echo $i ; done
a
b
c
d
e
The result should be:
结果应该是:
for i in ${X[@]} ; do echo $i ; done
a b
c
d e
回答by SiegeX
You need to change your Internal Field Separatorvariable (IFS) to a newline first.
您需要先将内部字段分隔符变量 ( IFS) 更改为换行符。
$ IFS=$'\n'; arr=( $(echo -e "a b\nc\nd e") ); for i in ${arr[@]} ; do echo $i ; done
a b
c
d e
回答by jaypal singh
Set the IFSto newline. By default, it is space.
将 设置IFS为newline。默认情况下,它是space.
[jaypal:~] while IFS=$'\n' read -a arry; do
echo ${arry[0]};
done < <(echo -e "a b\nc\nd e")
a b
c
d e

