1

I want to get a part in every line of a regular file. For this purpose I've used the program awk in my script. I need to put each part in an array. Something like this works:

declare -i j=1
awk 'BEGIN { FS="|" } { a[j]=$6; ((j++)) }' myFile

but I have a problem after in the script, when I need to use the array. Indeed the array in the awk block isn't seen by the remaining lines of the script -- the lines outside that block. How can this problem be solved?

2
  • 3
    Your array ceases to exist after the awk script terminates. The variable j inside and outside of the awk script refer to two different things. Commented May 31, 2017 at 16:43
  • 2
    As an aside: While ((j++)) works in awk too, there's no reason for enclosing the expression in parentheses (unlike in bash). Commented May 31, 2017 at 16:58

1 Answer 1

5

As Tom Fenech points out, shell code and awk scripts are separate worlds with separate variables that know nothing of each other.
(More generally, any external utility runs in a child process and therefore cannot modify the calling shell's environment.)

In order to read awk output into a bash array, you must read awk's stdout output.

In Bash v4+, you can do the following:

readarray -t a < <(awk 'BEGIN { FS="|" } { print $6 }' myFile)

This creates Bash array "${a[@]}" from the individual lines in awk's stdout output.

Note the use of a process substitution (<(...)) to provide input to readline via stdin (<), which ensures that the array remains in scope in the rest of the script.

Sign up to request clarification or add additional context in comments.

1 Comment

@Bento: Got it. One additional thing worth noting is that process substitutions aren't POSIX compliant, so they won't work with scripts that target /bin/sh rather than /bin/bash.

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.