根据换行符将命令输出行存储到数组中

时间:2014-03-04 07:35:43

标签: linux bash shell unix awk

我有一个变量如下&我执行某些操作以逐个打印输出,如下所述。

a="My name is A. Her Name is B. His Name is C"
echo "$a" | awk -F '[nN]ame |\\.' '{for (i=2; i<=NF; i+=2) print $i}'

输出

is A
is B
is C

当我将结果存储到数组中时,它将space视为数组分隔符并存储值。但我想将输出的每一行存储到每个数组索引值,如下所示

x=($(awk -F '[nN]ame |\\.' '{for (i=2; i<=NF; i+=2) print $i}' <<< "$a"))

输出,

${x[0]} = is
${x[1]} = A
..and so on...

我的期望是

${x[0]} = is A
${x[1]} = is B
${x[2]} = is C

echo ${#x[@]} = 6;它应该是= 3

2 个答案:

答案 0 :(得分:2)

OK try below:

i=0
while read v; do
    x[i]="$v"
    (( i++ ))
done < <(awk -F '[nN]ame |\\.' '{for (i=2; i<=NF; i+=2) print $i}' <<< "$a")

答案 1 :(得分:2)

您还可以使用mapfile命令(bash版本4或更高版本):

tempX=$(awk -F '[nN]ame |\\.' '{for (i=2; i<=NF; i+=2) print $i}' <<< "$a")
mapfile -t x <<< "$tempX"

~$ echo "${x[0]}"
is A