【问题标题】:gawk: why doesn't "next;" suppress lines matching a pattern?gawk:为什么不“下一个;”抑制与模式匹配的行?
【发布时间】:2018-10-24 16:14:49
【问题描述】:

我有以下 awk 程序:

/.*needle.*/
{
    if ($0 != "hay needle hay")
    {
        print "yay: ", $1;
        next;
    }

    print "ya2";
    next;
}

{
    print "no";
    next;
}

我在GNU Awk 4.2.1, API: 2.0 中以gawk -f test.awk < some.log > out.log 运行它。

一些日志:

hay hay hay
hay needle hay
needle
hay hay
hay
hay

out.log:

yay:  hay         
hay needle hay    
ya2               
needle            
yay:  needle      
yay:  hay         
yay:  hay         
yay:  hay         

我希望它只打印“ya2-new line-yay: needle”。

这引发了一些问题:

【问题讨论】:

  • 我在不同的数据上尝试了一个非常相似的表格:awk '/424/ {if (NR==3) {print;next;}print NR;next;} {print "no";}' 输出符合预期(如果“424”在该行中,则打印行号,但在第 3 行打印该行时除外。“否" 以其他方式打印。)也傻眼。
  • 我认为fields[1] 是一些..construct 我不知道这是有道理的。 $1,您在上面使用的当然是打印第一列的正常方式。
  • 在最小化 MCV 时破坏它。让我解决它。

标签: shell awk gawk


【解决方案1】:

您似乎是Allman indentation style 的粉丝。我假设if ($0 != ... 块只应该在记录匹配needle 的地方运行——您需要将左大括号放在与模式相同的行上。

/.*needle.*/ {
    if ($0 != "hay needle hay")
    {
        print "yay: ", $1;
        next;
    }

    print "ya2";
    next;
}

输出:

no
ya2
yay:  needle
no
no
no

在 awk 中,换行符是一个终止符,就像分号一样。

你现在拥有的是:

# if the line matches "needle", print it verbatim
/.*needle.*/     

# And **also**, for every line, do this:
{
    if ($0 != "hay needle hay")
    {
        print "yay: ", $1;
        next;
    }

    print "ya2";
    next;
}

【讨论】:

  • 我刚刚意识到这一点,因为我意识到他的输入是有效的,直到我让它不是单行的:)
  • 我鼓励您浏览awk tag info page
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 2012-09-17
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
相关资源
最近更新 更多