首页 > 解决方案 > awk:为什么匹配函数打印匹配的行而不提及打印它

问题描述

我有以下内容:

NODE_1
port 1
description blah
port 2
description blah blah
NODE_2
port 1
description blah
port 2
description blah
NODE_3
port 1
port 2
NODE_4
port 1
port 2
NODE_5
port 1
port 2
NODE_6
port 1
description blahdy blah
port 2
description floop-a-doop

我正在尝试打印 NODE 的前三个匹配项的匹配属性

awk 'BEGIN{count=0}
    match($0,/NODE/,a)
    {
    if(RSTART != 0){
        print "*******************************"
        for (i in a)
        print i"-->"a[i]
        count++;
        print "count-->"count;    
        print "*******************************"
        }
    if (count >= 3)
        {
        exit
        }
    }' awksampledata5.txt

输出是

NODE_1
*******************************
0start-->1
0length-->4
0-->NODE
count-->1
*******************************
NODE_2
*******************************
0start-->1
0length-->4
0-->NODE
count-->2
*******************************
NODE_3
*******************************
0start-->1
0length-->4
0-->NODE
count-->3
*******************************

我不想打印 NODE_1、NODE_2 和 NODE_3。但我不知道它是如何被打印出来的。

回答编辑代码:

$ awk 'BEGIN{count=0}
        match($0,/NODE/,a){
        if(RSTART != 0){  <-- this matters  new lines matters.
            print "*******************************"
            for (i in a)
            print i"-->"a[i]
            count++;
            print "count-->"count;
            print "*******************************"
            }
        if (count >= 3)
            {
            exit
            }
        }' awksampledata5.txt
*******************************
0start-->1
0length-->4
0-->NODE
count-->1
*******************************
*******************************
0start-->1
0length-->4
0-->NODE
count-->2
*******************************
*******************************
0start-->1
0length-->4
0-->NODE
count-->3
*******************************

标签: awk

解决方案


换行很重要。这个:

match($0,/foo/)
{ bar() }

与以下任何一个都不相同:

match($0,/foo/) { bar() }

match($0,/foo/) {
    bar()
}

第一个脚本说

If "foo" exists in $0 then print the current record.
Call bar().

而另外两个说:

If "foo" exists in $0 then call bar().

推荐阅读