如何在bash中逐行将命令输出转换为数组?

时间:2022-12-23 15:42:38

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

2 个解决方案

#1


13  

You need to change your Internal Field Separator variable (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

#2


0  

Set the IFS to newline. By default, it is space.

将IFS设置为换行符。默认情况下,它是空间。

[jaypal:~] while IFS=$'\n' read -a arry; do 
echo ${arry[0]}; 
done < <(echo -e "a b\nc\nd e")
a b
c
d e

#1


13  

You need to change your Internal Field Separator variable (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

#2


0  

Set the IFS to newline. By default, it is space.

将IFS设置为换行符。默认情况下,它是空间。

[jaypal:~] while IFS=$'\n' read -a arry; do 
echo ${arry[0]}; 
done < <(echo -e "a b\nc\nd e")
a b
c
d e