Sed基本語法


sed使用簡單,我們可以提供sed命令直接在命令列或具有sed命令的文字檔案的形式。本教學講解呼叫sed的例子,有這兩種方法:

Sed 命令列

以下是我們可以指定單引號在命令列sed命令的格式如下:

sed [-n] [-e] 'command(s)' files 

例子

考慮一下我們有一個文字檔案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

首先,讓我們不帶任何命令使用sed檔案的完整顯示內容如下:

[jerry]$ 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

現在,我們從上述檔案中顯示將看到sed的delete命令刪除某些行。讓我們刪除了第一,第二和第五行。在這裡,要刪除給定的三行,我們已經指定了三個單獨的命令帶有-e選項。

[jerry]$ sed -e '1d' -e '2d' -e '5d' books.txt 

執行上面的程式碼,會得到如下結果:

3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
6) A Game of Thrones, George R. R. Martin, 864 

sed指令碼檔案

下面是第二種形式,我們可以提供一個sed指令碼檔案sed命令:

sed [-n] -f scriptfile files

首先,建立一個包含在一個單獨的行的文字commands.txt檔案,每次一行為每個sed命令,如下圖所示:

1d 
2d 
5d 

現在,我們可以指示sed從文字檔案中讀取指令和執行操作。這裡,我們實現相同的結果,如圖在上述的例子。

[jerry]$ sed -f commands.txt books.txt

執行上面的程式碼,會得到如下結果:

3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
6) A Game of Thrones,George R. R. Martin, 864 

sed標準選項

sed支援可從命令列提供下列標準選擇。

 -n 選項

這是模式緩衝區的預設列印選項。 GNU sed直譯器提供--quiet,--silent選項作為 -n選項的替代。

例如,下面 sed 命令不顯示任何輸出:

[jerry]$ sed -n '' quote.txt 

-e 選項

-e選項的編輯選項。通過使用此選項,可以指定多個命令。例如,下面 sed 命令列印每行兩次:

[jerry]$ sed -e '' -e 'p' quote.txt

執行上面的程式碼,會得到如下結果:

There is only one thing that makes a dream impossible to achieve: the fear of failure. 
There is only one thing that makes a dream impossible to achieve: the fear of failure. 
 - Paulo Coelho, The Alchemist 
 - Paulo Coelho, The Alchemist

-f 選項

-f選項是用來提供包含sed命令的檔案。例如,我們可以按如下方法通過檔案指定一個列印命令:

[jerry]$ echo "p" > commands.txt 
[jerry]$ sed -n -f commands quote.txt

執行上面的程式碼,會得到如下結果:

There is only one thing that makes a dream impossible to achieve: the fear of failure. 
 - Paulo Coelho, The Alchemist