Sed模式範圍

本教程介紹如何sed處理一個模式範圍。模式範圍可以是一個簡單的文本或複雜的正則運算式。我們將開始使用下列內容的文本檔books.txt:

1) A Storm of Swords, George R. R. Martin, 1216
2) The Two Towers, J. R. R. Tolkien, 352
3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
6) A Game of Thrones, George R. R. Martin, 864

下麵的例子列印的作者所有書籍 Paulo Coelho

[jerry]$ sed -n '/Paulo/ p' books.txt

執行上面的代碼,會得到如下結果:

3) The Alchemist, Paulo Coelho, 197
5) The Pilgrimage, Paulo Coelho, 288

Sed通常運行在每一行,並只列印那些符合使用模式的給定條件的行。

我們還可以將一個模式範圍,地址範圍。下麵的例子列印起始行具有Alchemist 的第一行匹配,直到第五行。

[jerry]$ sed -n '/Alchemist/, 5 p' books.txt

執行上面的代碼,會得到如下結果:

3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288

可以使用美元符號($)發現的模式第一次出現後列印的所有行。下麵的示例查找字串Fellowship的第一次出現,並立即列印該檔中的其餘行

[jerry]$ sed -n '/The/,$ p' books.txt

執行上面的代碼,會得到如下結果:

4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
6) A Game of Thrones, George R. R. Martin, 864

也可以指定多個模式範圍使用逗號(,)運算符。下麵的例子列印所有模式 Two 和 Pilgrimage 之間存在的行。 

[jerry]$ sed -n '/Two/, /Pilgrimage/ p' books.txt 

執行上面的代碼,會得到如下結果:

2) The Two Towers, J. R. R. Tolkien, 352
3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288

此外,我們還可以在模式範圍使用的加號(+)運算。下麵的例子中發現模式Two第一次出現,並列印它之後的下一個4行。

[jerry]$ sed -n '/Two/, +4 p' books.txt

執行上面的代碼,會得到如下結果:

2) The Two Towers, J. R. R. Tolkien, 352
3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
6) A Game of Thrones, George R. R. Martin, 864

在這裏,只給出了幾個例子來熟悉sed。可以自己結合上面例子寫幾個例子試試。


上一篇: sed模式緩衝區 下一篇: Sed基本命令