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

上一篇: sed工作流程 下一篇: Sed迴圈