2016-01-24 45 views
0

我有一個簡單的問題。我有一個包含一個文件:(「的隔壁FOO中的*」澄清之間哪些部分我想要的結果從,我添加* s爲未在文件中。)搜索兩個圖案之間的多行文字

more random text 

*foo* 
there 
is 
random 
text 
here 
*foo* 

foo 
even 
more 
random 
text 
here 
foo 
more random text 

我只想打印foo的前兩個實例之間的多行。

我試圖尋找讓「富」只出現一次然後將其刪除的方法。但我沒有那麼遠。然而,我確實找到了使用sed'/ foo /,/ foo/p'刪除所有「更多隨機文本」的方法,但我無法找到使用sed或awk的方式來匹配和打印輸出。

任何人都可以幫我嗎?

回答

0
$ awk '/foo/{++c;next} c==1' file 
there 
is 
random 
text 
here 

$ awk '/foo/{++c;next} c==3' file 
even 
more 
random 
text 
here 

或GNU AWK多焦RS你可以這樣做:

$ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==2' file 
there 
is 
random 
text 
here 

$ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==4' file 
even 
more 
random 
text 
here 

印刷的其他方式見https://stackoverflow.com/a/17914105/1745001後一個條件爲真。

+0

請解釋一下你怎麼想它的意思相同 – Sadhun

+0

背後的邏輯是什麼?我會很樂意回答具體的問題,但它有點像解釋一個Hello World程序,所以你需要幫助。 –

0

由於檢查「富」(使用/foo/)是比較昂貴的,下面避免了檢查,並與所有awk小號名副其實的工作:

awk 'c==2 {next} /foo/{++c;next} c==1' file 
1

隨着SED:

$ sed -n '/foo/{:a;n;/foo/q;p;ba}' infile 
there 
is 
random 
text 
here 

解釋:

/foo/ {  # If we match "foo" 
    :a  # Label to branch to 
    n  # Discard current line, read next line (does not print because of -n) 
    /foo/q # If we match the closing "foo", then quit 
    p  # Print line (is a line between two "foo"s) 
    ba  # Branch to :a 
} 

一些SEDS抱怨括號我n單線;在這種情況下,這應該工作:

sed -n '/foo/ { 
    :a 
    n 
    /foo/q 
    p 
    ba 
}' infile 
+0

謝謝你對我的問題所做的貢獻。愛sed和awk兩者。不是他們的專家,但我很高興我和其他人可以選擇。 –