technopathe technopathe - 6 months ago 11
Bash Question

using variable defined outside Awk

I have codded the following lines :

ARRAY=($(awk 'FS = ";" {print $3}' file.txt))

LINE_CREATOR=`echo "aaaa;bbbb;cccccccc" |

'{awk -F";"};


for (i in ARRAY)

print $'${ARRAY['i']}'



the File.txt looks like


Explanation :

the array contains the value : 3 1 2

so the loop will loop on the array , and extract fields $3 $1 $2 from the "aaaa;bbbb;cccccccc" using awk

and the final output should be this


I still have some errors while launching my script.


I'm making a few guesses here but I think that this does what you want:

$ echo "aaaa;bbbb;cccccccc" | awk -F\; 'NR == FNR { n = split($0, a); next } 
{ printf "%s", a[$3] } END { print "" }' - file

NR == FNR means that the block is only run for the first input. - as an argument tells awk to read first from standard input. The string is split on FS (;) into the array a. next skips the rest of the script.

The second block is only run for the second input (the text file). The values in the third field are used to print the elements in the array a.