2013-10-30 63 views
1

我有以下文件:使用正則表達式

$ cat file 
> First line 
> Second line 
> Third line 
> Fourth and last line 
> First line 
> Second line 
> Third line 
> Fourth and last line 

我要打印第3行,很簡單:

$ sed -n '1,3p' file 
> First line 
> Second line 
> Third line 

現在我想從發生First打印到發生Third

$ sed -n '/First/,/Third/p' file 
> First line 
> Second line 
> Third line 
> First line 
> Second line 
> Third line 

啊!不是我想要的,我只想要第一次出現匹配的圖案範圍。當我有正則表達式作爲我的地址時,我該怎麼做?

回答

3

追加最終圖案作爲退出條件:

sed -n '/First/,/Third/p; /Third/q' file 

輸出:

> First line 
> Second line 
> Third line 
2

你可以這樣做與awk

awk '!f; /Third/ {f=1}' file 
> First line 
> Second line 
> Third line 

或者更短,更好,因爲它停止後發現處理文件。

awk '1; /Third/ {exit}' file 

或者如果需要從first採取third

awk '/First/ {f=1} f; /Third/ {exit}' file 
2

你可以試試這個sed

sed -n '/First/{:loop; $!N; /Third/{p;q}; b loop;}' file 
2

相信AWK可以幫助你做到這一點

awk '/First/{found=1} found{print; if(/Third/) exit}' file