awk的正则表达式匹配模式可以放置在动作行的开口括号上方,还是必须在同一行上?

问题描述 投票:1回答:1

我正在认真研究awk以编写一个git diffn实现,该实现将显示git diff的行号,我想确认this Wikipedia page on awk是否错误:

(pattern)
{
   print 3+2
   print foobar(3)
   print foobar(variable)
   print sin(3-2)
}

输出可能会发送到文件:

(pattern)
{
   print "expression" > "file name"
}

或通过管道:

(pattern)
{
   print "expression" | "command"
}

注意(pattern)在开孔大括号上方。我敢肯定这是错误的,但是在编辑页面之前需要先确定一下。我认为页面应该看起来是这样的:

/regex_pattern/ {
    print 3+2
    print foobar(3)
    print foobar(variable)
    print sin(3-2)
}

输出可能会发送到文件:

/regex_pattern/ {
    print "expression" > "file name"
}

或通过管道:

/regex_pattern/ {
    print "expression" | "command"
}

这里是“证明”它的测试。我使用的是Linux Ubuntu 18.04。

test_awk.sh

gawk \
'
BEGIN
{
    print "START OF AWK PROGRAM"
}
'

测试和错误输出:

$ echo -e "hey1\nhello\nhey2" | ./test_awk.sh
gawk: cmd. line:3: BEGIN blocks must have an action part

但与此:

test_awk.sh

gawk \
'
BEGIN {
    print "START OF AWK PROGRAM"
}
'

效果很好!:

$ echo -e "hey1\nhello\nhey2" | ./test_awk.sh
START OF AWK PROGRAM

另一个示例(无法提供预期的输出):

test_awk.sh

gawk \
'
/hey/ 
{
    print $0
}
'

错误输出:

$ echo -e "hey1\nhello\nhey2" | ./test_awk.sh
hey1
hey1
hello
hey2
hey2

但是像这样:

gawk \
'
/hey/ {
    print $0
}
'

它按预期工作:

$ echo -e "hey1\nhello\nhey2" | ./test_awk.sh
hey1
hey2
bash awk
1个回答
0
投票

您可以在示例中看到,可以在语句末尾使用分行代替分号而不是分号。当你有

/regex/
{ ...
}

它等效于/regex/; {...},它等于测试行为时的/regex/{print $0} {...}

请注意,BEGINEND是特殊标记,它们明确需要操作语句,因为对于BEGIN{print $0}不可能作为默认操作。这就是为什么大括号应位于同一行上的原因。也许是出于方便,但这都是一致的。

© www.soinside.com 2019 - 2024. All rights reserved.