thecomebackid thecomebackid - 4 months ago 16
Bash Question

passing for loop index into awk

I am trying to pass a for loop index i into awk but keep getting unexpected token awk errors.

First I tried using the -v option within awk:

for i in "${myarray}"
awk -v var=$i '/var/{print}' myfile.dat
done


I also tried calling the variable directly using single quotes:

for i in "${myarray}"
awk '/'"$i"'/{print}' myfile.dat
done


My end goal is to learn how to pass a for loop index variable through awk as the search pattern. I'd like the above code to search through
myfile.dat
and print lines which contain the strings in
myarray
.

Answer

There are 2 problems:

  1. Array traversing should be like this for i in "${myarray[@]}"
  2. awk treats text between /.../ as regex literal, to use a variable use $0 ~ var.

Your code should be:

for i in "${myarray[@]}"; do
   awk -v var="$i" '$0 ~ var' myfile.dat
done

{print} is default action in awk that you can omit as shown above.