Storing command output lines into array based on n

2019-07-12 02:27发布

I have a variable as below & i perform certain operations to print the output one by one as mentioned below.

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}'

The output is

is A
is B
is C

When I store the results into an array, it considers space as array separator and stores value. but i want to store the each line of the output to each array index values as below

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

out puts ,

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

What i expect is

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

Also echo ${#x[@]} = 6 ; It should be = 3

2条回答
可以哭但决不认输i
2楼-- · 2019-07-12 02:58

You can also use the mapfile command (bash version 4 or higher):

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

~$ echo "${x[0]}"
is A
查看更多
姐就是有狂的资本
3楼-- · 2019-07-12 03:01
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")
查看更多
登录 后发表回答