0

I want to print $2 however inside a for loop. I tried with the following

for i in {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,21}; do
awk '{ print $${i} }' COLVAR >tmp_${i}
done

It gives syntax error. I tried also with ${${i}} but still the syntax error. I am not sure what is wrong.

1 Answers1

0
$ cat file
a b c d e

To use shell variables in awk, use -v:

$ for i in 2 3 4; do awk -v i=$i '{ print $i }' file; done
b
c
d

Usually the best is to do something like this entirely in awk:

$ awk 'BEGIN { split("2 3 4", a) } { for (i in a) print $i }' file
a
b
c
jas
  • 10,715
  • 2
  • 30
  • 41