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。可以自己结合上面例子写几个例子试试。

posted @ 2016-02-15 16:47  天堂小说  阅读(323)  评论(0编辑  收藏  举报