Awk print variable

In this script, I want awk to print the variables $file , $f , $order and sum/NR (all on one line)

 #!/bin/bash for file in pmb_mpi tau xhpl mpi_tile_io fftw ; do for f in 2.54 1.60 800 ;do if [ ${f} = 2.54 ] then for order in even odd ; do # echo ${file}_${f}_${order}_v1.xls >> P-state-summary.xls awk '{sum+=$2} END {print ${file}_${f}_${order}_v1.xls, sum/NR}' ${file}_${f}_${order}_v1.xls >> P-state-summary.xls done else # echo ${file}_${f}_v1.xls >> P-state-summary.xls awk '{sum+=$2} END {print ${file}_${f}_v1.xls , sum/NR}' ${file}_${f}_v1.xls >> P-state-summary.xls fi done done 

Do any of you kindly help me with this?

+2
scripting awk printing
source share
2 answers

You can do it:

 echo -n "${file}_${f}_${order}_v1.xls " >> P-state-summary.xls # or printf "${file}_${f}_${order}_v1.xls " >> P-state-summary.xls awk '{sum+=$2} END {print sum/NR}' "${file}_${f}_${order}_v1.xls" | tee "${file}_${f}_avrg.xls" >> P-state-summary.xls 

Using echo -n or printf without "\ n" prints text without a new line, so the output of the awk command will follow it on the same line. I added a space as a separator, but you could use something.

Using tee will allow you to write your output to separate files and the resulting file, using only one awk call for each input (order) file.

+1
source share

awk does not exit and receives shell variables for you, you must pass them as awk variables:

 pax> export x=XX pax> export y=YY pax> awk 'BEGIN{print x "_" y}' _ pax> awk -vx=$x -vy=$y 'BEGIN{print x "_" y}' XX_YY 

There is another way to do this using double quotes instead of single quotes (so bash replaces values ​​before awk sees them), but then you need to start escaping the $ characters and all sorts of other things in your awk command:

 pax> awk "BEGIN {print \"${x}_${y}\"}" XX_YY 

I prefer to use explicit variable creation.

By the way, there is another solution to your previous related question here that should work.

+3
source share

All Articles