如何在ksh shell脚本中将shell变量传递给awk?

时间:2015-02-24 00:18:03

标签: shell awk ksh

我想知道如何将shell变量传递给awk ..可以请一些人帮忙。

m = 10 //这是shell vairable

awk -F, -v outfile="$outfile" '
    {
    printf("%14s Code %s %7s  %\047.2f\n"," ", $1," ",$2) >> outfile
    r[NR] = $1
    c[NR] = $3
   }
  END {printf("%14s Total Amount %7s %d \n "," "," ",$m) >> outfile

  }' trancumt.txt

请告诉我,我们是否有办法做到这一点..

2 个答案:

答案 0 :(得分:0)

稍微更改字符串以允许替换:

END {printf("%14s Total Amount %7s %d \n "," "," ",$m) >> outfile

END {printf("%14s Total Amount %7s %d \n "," "," ",'$m') >> outfile

或者(见注释),将行更改为

END {printf("%14s Total Amount %7s %d \n "," "," ",m) >> outfile

添加选项

-v m=$m

答案 1 :(得分:0)

您可以多次使用选项-v将多个变量从shell传递到awk。正确的命令是:

awk -F, -v outfile="$outfile" -v m="$m" '<awk commands>'

检查以下示例以确定其有效:

m="10"
outfile="foo.bar"
awk -v m="$m" -v outfile="$outfile" 'BEGIN{print m, outfile; exit}'

输出:

10 foo.bar