2

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"

5
  • 1
    You got an answer but the shell script doesn't make sense. All you need to print lines that contain something other than zeros or spaces in awk is awk '/[^0[:space:]]/' "$line", assuming $line contains the name of an input file as it appears to from your script. Commented Sep 26, 2014 at 16:46
  • 1
    @ed, good thought, but to be pedantic, there are other "zero" values: printf "%s\n" 0 0.0 0e0 0e-1 | awk '$1 != 0' Commented Sep 26, 2014 at 17:13
  • @glennjackman also a good point. He didn't say all equal to zero though, he said all 0s so I think my suggestion would work. Some sample input and expected output would tell us for sure. Commented Sep 26, 2014 at 17:22
  • I agree. Sometimes I nitpick to a fault. Just ask my wife ... Commented Sep 26, 2014 at 17:22
  • The $ at the end of each line is puzzling; I think they should not be present. Commented Sep 26, 2014 at 21:37

2 Answers 2

2

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.

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

Comments

2

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.

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.