In this script , I want awk to print the variables $file, $f, $order and sum/NR (all in a single row)

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 ]
        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
#       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

Colud anyone of you kindly help me with this ?

Was it helpful?


You can do this:

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 a "\n" will output the text without a newline 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 anything.

Using tee will allow you to write your output to the individual files and the summary file using only one awk invocation per input (order) file.


awk doesn't go out and get shell variables for you, you have to pass them in as awk variables:

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

There is another way of doing it by using double quotes instead of single quotes (so that bash substitutes the values before awk sees them), but then you have to start escaping $ symbols and all sorts of other things in your awk command:

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

I prefer to use explicit variable creation.

By the way, there's another solution to your previous related question here which should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow