gawk:为什么没有'#34;"抑制与模式匹配的行?

时间:2018-05-14 22:26:25

标签: shell awk gawk

我有以下awk程序:

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

    print "ya2";
    next;
}

{
    print "no";
    next;
}

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

some.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         

我希望它只打印&#34; ya2-new line-yay:needle&#34;。

这提出了一些问题:

1 个答案:

答案 0 :(得分:4)

你似乎是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;
}
相关问题