2

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 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

But it returns full data echo ${x[0]} = is A is B is C
Wrap argument of echo in quotes echo "${x[0]}"
now returns one by one... i want only the first line to in the first array.. (see my question) $ echo "${x[0]}" is A is B is C [
@logan For that you need bash version 4 or higher.
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")

2 Comments

But it returns full data echo ${x[0]} = is A is B is C
i expect ${x[0]} = is A ${x[1]} = is B ${x[2]} = is C

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.