流编辑器 - 模式范围

在上一章中,我们了解了SED如何处理地址范围.本章介绍SED如何处理模式范围.模式范围可以是简单文本或复杂正则表达式.让我们举个例子.以下示例打印作者Paulo Coelho的所有书籍.

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


在执行上述代码时,您会得到以下结果:

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


在上面的例子中,SED对每个人进行操作并且只打印那些与字符串Paulo匹配的行.

我们还可以将模式范围与地址范围组合在一起.以下示例打印从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


我们可以使用Dollar($)字符在找到第一次出现的模式后打印所有行.以下示例查找模式的第一个匹配项并立即打印文件中剩余的行

[jerry]$ sed -n '/The/,$ 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


我们还可以指定更多使用逗号(,)运算符的一个模式范围.以下示例打印模式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.您可以通过自己尝试一些示例来了解更多信息.