Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a bash associative array in awk

Tags:

bash

shell

awk

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!

like image 884
Ricketyship Avatar asked Mar 05 '13 07:03

Ricketyship


3 Answers

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
like image 84
chepner Avatar answered Sep 21 '22 00:09

chepner


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.

like image 40
Daniel Kamil Kozar Avatar answered Sep 19 '22 00:09

Daniel Kamil Kozar


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.

like image 27
cdarke Avatar answered Sep 20 '22 00:09

cdarke