How to print filename in awk?

Viewed 203

I would like to print filename and then the value of $7 in the cycle. What is wrong please? with '"i"'

for i in r*; do
    awk 'FNR == 2 {print '"i"', $7}' r* > out
done

OUTPUT after advise

fdfadfasdfa     0.00775                 0.00644                 6298
dsafdsfsaf      0.00705                 0.00574                 14173
dasfdsafdafd        0.00716                 0.00597                 22948
dafadsafdafsdf      0.00859                 0.00679                 5210
dafadsfsa       0.00705                 0.00576                 11098
2 Answers

Could you please try following. You need not to use for loop for it.

awk 'BEGIN{OFS="\t\t"} FNR==2{print FILENAME, $7}' r*  | column -t > out

In case you have GNU awk you can use nextfile to save many cycles and directly jump to next file once condition met like:

awk 'BEGIN{OFS="\t\t"} FNR==2{print FILENAME, $7; nextfile}' r*  | column -t > out

To set \t\t as tab separator for output set OFS in BEGIN section. Add | column -t in output to get it correct format of TAB.

Remove BEGIN{OFS="\t\t"} in case it is NOT required since column command is added(OP asked for TAB in output so that was added for it).

Since you're relying on bash to supply $i you need to include a dollar sign. Also the single and double quotes should be swapped. Awk needs to see the double quotes so they need to be inside the single quotes.

for i in r*; do
    awk 'FNR == 2 {print "'$i'", $7}' r* > out
done

Note that this isn't safe if $i could contain special characters. It's best not to expand bash variables directly inside awk scripts. You get quoting problems, whitespace problems; it's a ticking time bomb.

It's better to use -v to pass bash variables to awk. It's safer and it avoids the quoting and escaping problem to boot. You can just write i, simple as that.

for i in r*; do
    awk -v i="$i" 'FNR == 2 {print i, $7}' r* > out
done
Related