Supose I have a loop (bash shell), following sort of structure:
for iter in `seq 1 to 5`
do
<bunch of stuff that generates a file called test.dat>
awk -v var="$iter" '{print $1 " " var}' test.dat > mod_test.dat
done
What I can't quite figure out is why awk is not writing out the current value of the $iter variable.
For example, test.dat might look like (say)
abcd
efgh
ijkl
mnop
I'm looking to end up with
abcd 1
efgh 2
ijkl 3
mnop 4
[Basically, I simply want to put the loop counter at the end of each line.]
But, my script so doesn't work, since the output file (mod_test.dat) is simply
abcd 5
efgh 5
ijkl 5
mnop 5
In other words, it is only appending the last value of the counter to each line. I know the counter is working (echo $iter in the loop shows it is incrementing).
What is the obvious thing I'm doing wrong? I've tried every trick I know to set the awk variable (var=$iter, var="$iter", var="$iter"....), without success. I'm an awk semi-newb, so apologies if this is at a level even below trivial.
Many thanks in advance.
awkitself. Also on another note: your seq command should beseq 1 5.test.dat > mod_test.datoverwrites the target file with the last iteration output of awk (which also isn't probably what you're after). Use>>to append to the target file.var=1and awk processes every record in the file and outputs to target file. Second iteration,var=2and awk processes every record in the file and outputs to target file. And so on. Lose the bash loop and use onlyawk '{print $0,NR}' fileis the quickest fix.Use grep to find the line in the listing containing value I need. Use awk to pull the value from that line,- you never need grep when you're using awk.grep 'foo' | awk '{bar}'=awk '/foo/{bar}'.