awk范围模式 - 在范围模式开始时做一些事情

时间:2012-07-04 10:52:55

标签: awk gawk

我需要知道,哪条线是与awk匹配范围模式的线。 假设我有以下输入:

some random text
some random text START this is first line I want to match with START
some random text
some random text
some random text
some random text START this line contains another START but I dont want matched this line
some random text
some random text END this line is last of my range
some random text
... input text countinues, more range matches can be found

我想如何匹配:

/START/,/END/ {
if ((index($0,"START"))) {
# do something when range starts
}
#do some other things
}

但后来我意识到,我的索引会在范围中间的第6行与START匹配。我想在START与index的第一场比赛之后举起一面旗帜,但是有一些像NR这样的全局变量更优雅的方式吗?

编辑:输入文本继续,可以找到更多的范围匹配,如果我提出标记或使用计数,我将不得不重置范围结束后的标记/计数(添加索引($ 0,“结束”)),我没有想

2 个答案:

答案 0 :(得分:0)

您可以先将所有内容读入数组,然后仅对其第一个元素进行操作。我不确定它是否可以比标记旗更漂亮。

答案 1 :(得分:0)

一种方式。尝试在范围内递增变量,仅当它等于1匹配范围的开头时。在第二个START行中,它将为5,并且不会成功检查i == 1

/START/,/END/ {
    ++i 
    if ( i == 1 ) { 
        print "Range starts"
    }   
    print "Other things"
}
相关问题