Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk to compare array string to string from awk

Tags:

bash

unix

awk

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.

like image 581
Bearforce96 Avatar asked Aug 06 '26 07:08

Bearforce96


2 Answers

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

like image 189
shellter Avatar answered Aug 07 '26 21:08

shellter


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 ... 
}'
like image 30
glenn jackman Avatar answered Aug 07 '26 21:08

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!