TonyW
TonyW

Reputation: 18875

integer variable in awk script

I have the following code in a shell script: to count the number of columns first (variable numCol), then plug it in the for-loop in the awk to check if all the values are all 0s in each line:

numCol=$(awk '{print NF}' $line | head -n 1)$
awk '{for (i=1; i<=$numCol; ++i) if($i != 0) {print;next}}' $line$

but, I got this error: awk: illegal field $(), name "numCol"

Upvotes: 2

Views: 3644

Answers (2)

Kent
Kent

Reputation: 195039

you messed up shell's variable and awk's varialbe

this example tells all:

awk -v awkVar="$shellVar" '{for(i=1;i<=awkVar;i++)...}' ...

Names could be different, but you should know which variable should be used in which context.

Upvotes: 2

anubhava
anubhava

Reputation: 785058

To pass $numCol shell variable to awk use -v option:

awk -v numCol=$numCol '{for (i=1; i<=numCol; ++i) if($i != 0) {print;next}}'

However if you show some example input/output data then we might be able to do this in one step itself.

Upvotes: 2

Related Questions