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

时间:2012-01-07 08:40:05

标签: arrays bash shell

我正在尝试将echo -e "a b\nc\nd e"之类的命令的输出转换为数组。

X=( $(echo -e "a b\nc\nd e") )

为每个新行和空格字符拆分输入:

$ echo ${#X[@]}
> 5

for i in ${X[@]} ; do echo $i ; done
a
b
c
d
e

结果应为:

for i in ${X[@]} ; do echo $i ; done
a b
c
d e

3 个答案:

答案 0 :(得分:14)

您需要先将内部字段分隔符变量(IFS)更改为换行符。

$ IFS=$'\n'; arr=( $(echo -e "a b\nc\nd e") ); for i in ${arr[@]} ; do echo $i ; done
a b
c
d e

答案 1 :(得分:0)

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

答案 2 :(得分:0)

<!-- WRONG FORMATTING -->

<a href='https://picsum.photos/' alt="Go to Lorem Picsim">
  <div class="col-lg-6 order-lg-2 text-white showcase-img" style="background-image: url('https://picsum.photos/200/300');"></div>
</a>

<!-- PROPER FORMATTING -->

<div class="col-lg-6 order-lg-2 text-white showcase-img">
  <a href='https://picsum.photos/' alt="Go to Lorem Picsim" style="background-image: url('https://picsum.photos/200/300');">
  </a>
</div>