[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [ask] awk - passing for loop bash variables to awk



Morning Star <morning.star.crew@gmail.com> writes:

>here is the desired output:
>line_1
>line_2
>line_3

>here is what i do:
>cat input | for (( i=1;i<=3;i++ )); do gawk -v var=$i 'NR == var { print}'; done

>but, the result is always:
>line_1

When awk runs, it reads its input until EOF. In your loop, the first run
of awk is consuming all the input from stdin (cat input) and printing
the first line. For the subsequent iterations through the loop, awk no
longer has anything to read - it gets EOF when attempting to read the first
line. This means the script never matches anything and will not print
anything.

You will need to have awk re-read the input each time:

for (( i=1;i<=3i++ )) ; do
  cat input | gawk -v var=$i 'NR == var { print; exit }'
done

I've added an "exit" to the awk script since after the action is executed,
there is clearly no more work to be done for the rest of the file, so it
make sense to terminate early.

"cat input | " is not needed - it's a useless use of cat, but I don't
know if you have it here as a representation of a more complex pipeline
that is not relevant to your question. If you are literally using
"cat input | ", you can replace it with either:

  gawk -v var=$1 '...' input

(i've remove the script for brevity).


Reply to: