Reputation: 18875
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
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
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