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

How to pass shell variables to awk in ksh shell script?

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

m=10 // 这是 shell 变量

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

  }' trancumt.txt

请问有办法做到吗..

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

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

您可以多次使用选项 -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