thecomebackid thecomebackid - 2 months ago 5
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

I also tried calling the variable directly using single quotes:

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

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
and print lines which contain the strings in


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

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