technopathe technopathe - 5 months ago 10
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";"};

END

for (i in ARRAY)
{

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

}

}'`


the File.txt looks like

1;8;3
4;6;1
7;9;2




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

ccccccccaaaabbbb




I still have some errors while launching my script.

Answer

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
ccccccccaaaabbbb

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.