- Sed 教程
- Sed - 主頁
- Sed - 概述
- Sed - 環境
- Sed - 工作流程
- Sed - 基本語法
- Sed - 迴圈
- Sed - 分支
- Sed - 模式緩衝區
- Sed - 模式範圍
- Sed - 基本命令
- Sed - 特殊字元
- Sed - 字串
- Sed - 管理模式
- Sed - 正則表示式
- Sed - 有用食譜
- Sed 有用資源
- Sed - 快速指南
- Sed - 有用資源
- Sed - 討論
流編輯器 - 模式範圍
在上一章中,我們學習了 SED 處理地址範圍的方式。本章介紹了 SED 如何處理模式範圍。模式範圍可以是簡單的文字或複雜的正則表示式。我們舉個例子。以下示例列印作者保羅·科埃略的所有書籍。
[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
我們還可以使用逗號(,)運算子指定多個模式範圍。以下示例列印介於模式 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。你始終可以透過自行嘗試一些示例來了解更多資訊。
廣告