
- Sed 教程
- Sed - 首頁
- Sed - 概述
- Sed - 環境
- Sed - 工作流程
- Sed - 基本語法
- Sed - 迴圈
- Sed - 分支
- Sed - 模式緩衝區
- Sed - 模式範圍
- Sed - 基本命令
- Sed - 特殊字元
- Sed - 字串
- Sed - 模式管理
- Sed - 正則表示式
- Sed - 實用技巧
- Sed 資源
- Sed - 快速指南
- Sed - 資源
- Sed - 討論
流編輯器 - 特殊字元
SED 提供兩個被視為命令的特殊字元。本章闡述了這兩個特殊字元的用法。
= 命令
= 命令處理行號。以下是 = 命令的語法:
[/pattern/]= [address1[,address2]]=
= 命令將行號及其內容寫入標準輸出流。以下示例對此進行了說明。
[jerry]$ sed '=' books.txt
執行上述程式碼後,您將得到以下結果:
1 1) A Storm of Swords, George R. R. Martin, 1216 2 2) The Two Towers, J. R. R. Tolkien, 352 3 3) The Alchemist, Paulo Coelho, 197 4 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5 5) The Pilgrimage, Paulo Coelho, 288 6 6) A Game of Thrones, George R. R. Martin, 864
讓我們列印前四行的行號和內容。以下命令列印帶有行號的前四行,其餘行不帶行號。
[jerry]$ sed '1, 4=' books.txt
執行上述程式碼後,您將得到以下結果:
1 1) A Storm of Swords, George R. R. Martin, 1216 2 2) The Two Towers, J. R. R. Tolkien, 352 3 3) The Alchemist, Paulo Coelho, 197 4 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 在模式匹配成功時列印行號。以下示例列印包含模式“Paulo”的行號。
[jerry]$ sed '/Paulo/ =' books.txt
執行上述程式碼後,您將得到以下結果:
1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864
你能猜到以下 SED 命令的作用嗎?
[jerry]$ sed -n '$ =' books.txt
執行上述程式碼後,您將得到以下結果:
6
是的,你答對了。它計算檔案中存在的總行數。讓我們解釋一下程式碼。在命令部分,我們使用了“$=”,它列印最後一行及其內容的行號。但是我們也提供了-n標誌,它抑制了模式緩衝區的預設列印。因此,只顯示最後一行號。
& 命令
SED 支援特殊字元 &。每當模式匹配成功時,此特殊字元都會儲存匹配的模式。它通常與替換命令一起使用。讓我們看看如何利用這個高效的功能。
book.txt 檔案中的每一行都有編號。讓我們在每一行的開頭新增“書號”字樣。以下示例對此進行了說明。
[jerry]$ sed 's/[[:digit:]]/Book number &/' books.txt
執行上述程式碼後,您將得到以下結果:
Book number 1) A Storm of Swords, George R. R. Martin, 1216 Book number 2) The Two Towers, J. R. R. Tolkien, 352 Book number 3) The Alchemist, Paulo Coelho, 197 Book number 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 Book number 5) The Pilgrimage, Paulo Coelho, 288 Book number 6) A Game of Thrones, George R. R. Martin, 864
這個例子很簡單。首先,我們搜尋數字的第一次出現,也就是行號(這就是我們使用 [[:digit:]] 的原因),SED 自動將匹配的模式儲存在特殊字元 & 中。在第二步中,我們在每個匹配模式之前,也就是每行之前插入“書號”字樣。
讓我們來看另一個例子。在 book.txt 檔案中,最後一個數字表示書的頁數。讓我們在前面新增“頁數 =”。為此,請查詢數字的最後一次出現,並將其替換為“頁數 = &”。這裡,& 儲存匹配的模式,即頁數。
[jerry]$ sed 's/[[:digit:]]*$/Pages = &/' books.txt
執行上述語法後,您將得到以下結果:
1) A Storm of Swords, George R. R. Martin, Pages = 1216 2) The Two Towers, J. R. R. Tolkien, Pages = 352 3) The Alchemist, Paulo Coelho, Pages = 197 4) The Fellowship of the Ring, J. R. R. Tolkien, Pages = 432 5) The Pilgrimage, Paulo Coelho,Pages = 288 6) A Game of Thrones, George R. R. Martin, Pages = 864
目前,只需記住[[:digit:]]*$ 查詢數字的最後一次出現。在“正則表示式”一章中,我們將更深入地探討正則表示式。