0

A simplified version of my code looks like the following:

declare -a DMN=(" " "200" "190" "180")
NRL=3

runDHFiles()
{
awk 'NR>13 {if ($4==$DMN[$i]) print $1, $2, $3, $4;}' domain_all.dat >> ddh_domain_${DMN[$i]}.dat
}

for ((i = 1; i <= NRL; i++ )); do
   runDHFiles
done

I'm trying to loop over a large Excel file and copy the rows where the domain flag (in column 4) equals a certain number.

If I do this, it works fine:

if ($4==200)

If I do this, it doesn't work:

if ($4==$DMN[$i])

How can I access value from the array in my loop for the equality statement?

Thanks,

Cole

1

One option is to pass the shell variable into awk, which avoids requoting:

awk 'NR>13 {if ($4==dmn) print $1, $2, $3, $4;}' dmn="${DMN[$i]}" domain_all.dat >> ddh_domain_${DMN[$i]}.dat

I'd be inclined to refactor your shell script, too, so that the variable is passed into your shell function:

declare -a DMN=(" " "200" "190" "180")
NRL=3

runDHFiles()
{
    local dmn="$1"
    awk 'NR>13 && $4==dmn {print $1, $2, $3, $4;}' dmn="$dmn" domain_all.dat >> "ddh_domain_${dmn}.dat"
}

for ((i=1; i<=NRL; i++ ))
do
   runDHFiles "${DMN[$i]}"
done
| improve this answer | |
0

If you change your quoting to allow the bash array variable to be "seen", this would improve it:

awk 'NR>13 {if ($4=="'"$DMN[$i]"'") print $1, $2, $3, $4;}' domain_all.dat >> ddh_domain_${DMN[$i]}.dat

That is, temporarily end the single-quoted part (and use double-quotes to make it a string for awk).

Alternatively (some prefer it) would be to use the -v option of awk to declare a variable, and use that in the script:

awk -v value=DMN[$i] 'NR>13 {if ($4==value) print $1, $2, $3, $4;}' domain_all.dat >> ddh_domain_${DMN[$i]}.dat
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.