Sed - 模式范围

  • 简述

    在上一章中,我们学习了 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($) 字符打印所有行。以下示例查找模式 The 的第一次出现并立即打印文件中的剩余行
    
    [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 
    
    我们还可以使用 comma(,) 运算符指定多个模式范围。下面的示例打印模式二和朝圣之间存在的所有行。
    
    [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
    
    此外,我们可以在模式范围内使用加号(+)运算符。下面的示例查找模式二的第一次出现,然后打印接下来的 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。您总是可以通过自己尝试一些示例来了解更多信息。