如果我不在 AWK 的 END 块中写“if”,为什么会出现语法错误?

Abi*_*ash 10 awk

这些天我正在学习 AWK 以进行文本处理。但是我对 AWK 语法非常困惑。我在维基百科上读到语法遵循这种格式:

(conditions) {actions}
Run Code Online (Sandbox Code Playgroud)

我假设我可以在 BEGIN 和 END 块中遵循相同的语法。但是当我运行以下脚本时出现语法错误。

awk 'BEGIN{}
(1 == 1) {print "hello";}
END{
(1==1) {print "ended"}}' $1
Run Code Online (Sandbox Code Playgroud)

但是,如果我在 END 块内进行一些更改并在条件前添加“if”,则它运行得很好。

awk 'BEGIN{}
(1 == 1) {print "hello";}
END{
if (1==1) {print "ended"}}' $1
Run Code Online (Sandbox Code Playgroud)

为什么必须在 END 块中写入 'if' 而在普通块中不需要它?

Ste*_*itt 25

AWK 程序是一系列规则,可能还有功能。规则被定义为一个模式(conditions)在你的格式中)后跟一个动作;要么是可选的。

BEGIN并且END特殊图案

因此在

BEGIN {}
(1 == 1) { print "hello"; }
END { if (1 == 1) { print "ended" } }
Run Code Online (Sandbox Code Playgroud)

模式是BEGIN, (1 == 1)(不需要括号),和END

模式(或没有模式,以匹配所有内容)之后的大括号内的块是actions。您不能编写这样的模式,每个块都由引入它的模式控制。动作中的条件必须指定为if语句(或其他条件语句while等)的一部分。

上面的动作是{}(空动作){ print "hello"; }、 和{ if (1 == 1) { print "ended" } }

包含{ (1 == 1) { print "ended" } }导致语法错误的块,因为(1 == 1)这里是一个语句,并且必须以某种方式与后面的语句分开;{ 1 == 1; { print "ended" } }将是有效的,但不会产生您想要的效果 -1 == 1将被评估,然后单独,{ print "ended" }.