2015-10-15 42 views
-2

我想在使用sed的文件中匹配一個模式時,保留幾行。 如果文件以下條目:如何在使用sed匹配模式時打印最後幾行?

This is the first line. 
This is the second line. 
This is the third line. 
This is the forth line. 
This is the Last line. 

因此,搜索模式,「最後」,並打印最後幾行..

回答

0

尋找「最後一個」使用sed和它管尾命令,打印最後n -n指定否。要從文件末尾讀取的行,這裏我正在讀取文件的最後兩行。

sed '/Last/ p' yourfile.txt|tail -n 2 

有關下載使用規章man tail。欲瞭解更多信息,

另外,|此處的符號被稱爲管道(未命名管道),它有助於進行進程間通信。因此,簡單地說,sed使用管道將數據傳送給tail命令。

0

我假設你的意思是「找到模式,並打印以前的幾行」。 grep是你的朋友:打印前3行:

$ grep -B 3 "Last" file 
This is the second line. 
This is the third line. 
This is the forth line. 
This is the Last line. 

-B n爲 「前」。還有-A n(「之後」)和-C n(之前和之後的「上下文」)。

+0

@potong,謝謝..這將工作! – SBC

0

這可能爲你工作(GNU SED):

sed ':a;$!{N;s/\n/&/2;Ta};/Last/P;D' file 

這將打印包含Last和前兩個行線。

N.B.這隻會在比賽前打印一行。也可以通過將2更改爲所需的多條線來顯示更多線條。