My question is, is it possible to assign a bash variable within an awk script.
i.e Assuming following is a shell script I have written,
declare -A sample_associative_array
awk -F'=' '{$sample_associative_array[$2]=$1}'  /tmp/sample.txt
given /tmp/sample.txt has:
abc=0
def=1
I tried
echo $sample_associative_array[0]
and it doesnt work.
Any help would be appreciated.
Cheers!
Not quite the same thing, but you can have awk output strings that can be used by the bash built-in command declare to populate an associative array. I'm not entirely sure why you would want to do this, though.
$ declare $( awk -F'=' '{print "aa["$2"]="$1}' sample.txt )
$ echo ${aa[0]}
abc
$ echo ${aa[1]}
def
                        You can't do that. Awk and Bash use totally different scopes of variables, and allowing one to use the variables declared in another one would be a great violation of process sovereignty.
What you're trying to do can be very simply done with Bash via using parameter expansion with removal of the prefix/suffix, e.g. ${parameter#word} and ${parameter%word}. Consult the Bash manual for more information.
Also, array references in Bash use other syntax : ${sample_associative_array[0]} is what you want.
No.  A child process cannot assign to a variable in the parent, you would have this issue regardless of the language.  awk cannot even directly read a bash associative array either, since you cannot export an array from bash (or any other shell that I know of). 
You will always get these kinds of problems when trying to mix languages.  General tip is to write the whole lot in either bash or awk, both are quite powerful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With