2012-07-04 84 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" 
}