2

I would like to make an array in bash that uses awk to compare a word to a string held in an array so far i have:

     name=( "name1" "name2" "name3" )
     num=0
     awk -F, '$2 == name[0] { num += $1 }; END { print num }'  ~Me/stuff/home.txt

for some reason this doesnt work but if i replace name[0] with "name1" it works fine. home.txt looks like

     81920,name1
     84985,name2
     11000,name3
     71111,name1
     etc...

Any help would be appreciated thankyou.

0

2 Answers 2

5

awk doesn't have access to your shell variables, especially when you use single quotes for your awk code. To go with the code you have, you could do

    awk -F, '$2 == "'"${name[0]}"'" { num += $1 }; END { print num }'  ~Me/stuff/home.txt

Above I have written dbl-quote single-quote dbl-quote surrounding the ${name[0]} variable. This allows the shell to interpolate the value from the shell environment into the body of the awk code. Note that to compare the value (using ==) with $2, it is best that the value is seen as a string inside of awk. So the comparsion made after the substitution of the shell variable is $2 == "name" { ...

You would find it instructive to run this code preceded by the shell debug/trace flags, set -vx. Turn off the trace/debug with set +vx after the code of interest.

But better to pass that value in with

awk  -F, -v name="${name[0]}" '$2 == name { num += $1 }; END { print num }'  ~Me/stuff/home.txt

output

153031

IHTH

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

2 Comments

I've answered your direct Q, and I'm very glad my answer helped you. But, be aware that awk could easily process all of the list you have mentioned in 1 process rather than calling awk 3 times. Maybe your problem is more complex than what you have shown, and it makes sense to call awk individually for each name, but if not, consider posting a revised question that describes your sources of data, the list to process (and describe it), and required output from those. Including some code will show that you have attempted to solve your problem (as you have done here) and get you help faster.
Thanks to @glennjackman for correcting the first set of code. I'll change the related comment to match. Good luck to all.
4

To pass a bash array to awk, you'll have to stringify the array and split it inside awk.

bash_array=( "some data" "with spaces" "but no commas" )
awk -v ary_data="$(IFS=,; echo "${bash_array[*]}")" '
    BEGIN {num_elements = split(ary_data, awk_array, /,/)}
    # ... do stuff with awk_array ... 
}'

Comments

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.