AWK:无法访问传递的参数
问题描述:
我从shell脚本调用myAwk.awk
像下面,AWK:无法访问传递的参数
awk -f myAwk.awk -v inputKeyword="SEARCH" file2.xml
$bash: cat myAwk.awk
BEGIN{
print "This is from awk script:" inputKeyword; //This prints SEARCH string. Fine.
}
/<record/{ i=1 }
i { a[i++]=$0 }
/<\/record>/ {
if (found) {
for (i=1; i<=length(a); ++i) print a[i] >> resultFile.xml
}
i=0;
found=0
}
/<keyword>inputKeyword<\/keyword>/ { found=1 } //Looks like the value for inputKeyword is not available here.
//There are no errors though.
我怎样才能使inputKeyword
值可用在我需要的地方?
答
您需要更改线路,
/<keyword>inputKeyword<\/keyword>/ { found=1 }
到
$0 ~ "<keyword>"inputKeyword"</keyword>" { found=1 }
如果匹配模式(regex
)在变量中,则不需要//
。 awk
将不会插入//
之间的内容。这将被视为只是一个字符串在那里。
+0
'$ 0'有什么价值?为什么我需要'$ 0'? – user2488578
+0
@ user2488578,'$ 0'将会有当前行。这是一个awk的内置变量。 – sat
答
按照手册页,你应该-f
前通过的选项:
SYNOPSIS
`gawk [ POSIX or GNU style options ] -f program-file [ -- ] file ...` `gawk [ POSIX or GNU style options ] [ -- ] program-text file ...`
你不能在'/.../'中使用它,使用'〜'来匹配。 –