2012-07-04 28 views
2

我需要知道,哪一行是与awk范围模式匹配的行。 假设我有以下输入: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,“结束”)),我是什么不想要

+1

我会用一个标志。 –

回答

0

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

0

单程。尝试在范围内增加一个变量,仅当它等于1时与范围的开始位置相匹配。在第二行START行中它将是5,并且不会成功执行检查i == 1

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