printing variable inside awk

情到浓时终转凉″ 提交于 2019-12-24 00:11:28

问题


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

#!/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

Colud anyone of you kindly help me with this ?


回答1:


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.




回答2:


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}'
XX_YY

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}\"}"
XX_YY

I prefer to use explicit variable creation.

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



来源:https://stackoverflow.com/questions/1825509/printing-variable-inside-awk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!