Bash – Use For Loop Variable in Other Commands

awkbashshell-script

I would like to run a for-loop, which computes the following task: Run awk 10 times, sum output and print final result. The code is attached below:

sum=0
for i in {1..10}
  do
  count=`awk '{if ($NF==$i) {print $NF}}' * | wc -l`
  sum=$[sum+count]
  echo $sum
done

The issue is, if I change $NF==$i to $NF==1, then the result is correct, but I would like to use the for-loop to run 10 times.

What is the issue in the code?

Best Answer

The issue here is that you are trying to get shell variable expansion inside single quotes ' ... '. However, inside single quotes, shell variable expansion is suspended (see e.g. this answer here or Lhunath & GreyCat's Bash Guide), which is the reason why this is actually recommended: as the $ performs a similar function in awk in dereferencing individual input fields (but where the field number can be expressed by a variable name as well, as in e.g. $NF), enclosing the program in single quotes avoids concurrent "variable expansions".

In your case, you can "import" the value into the awk program with

awk -v fieldnr="$i" '{if ($NF==fieldnr) {print $NF}}'

Still, it would appear that your problem can be solved entirely in awk, so maybe you want to explain what you want to accomplish in more detail and we can try to find a more elegant (and possibly faster) way; it may be reasonable to open another question, though ...

Related Question