鍍金池/ 教程/ Linux/ Sed基本語法
Sed字符串
Sed實用功能
Sed管理模式
sed環(huán)境設(shè)置
sed模式緩沖區(qū)
Sed循環(huán)
Sed模式范圍
Sed教程
Sed正則表達式
Sed分支
Sed基本語法
sed工作流程
Sed特殊字符
Sed基本命令

Sed基本語法

sed使用簡單,我們可以提供sed命令直接在命令行或具有sed命令的文本文件的形式。本教程講解調(diào)用sed的例子,有這兩種方法:

Sed 命令行

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

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

例子

考慮一下我們有一個文本文件books.txt待處理,它有以下內(nèi)容:

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文件的完整顯示內(nèi)容如下:

[jerry]$ sed '' books.txt

執(zhí)行上面的代碼,會得到如下結(jié)果:

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

現(xiàn)在,我們從上述文件中顯示將看到sed的delete命令刪除某些行。讓我們刪除了第一,第二和第五行。在這里,要刪除給定的三行,我們已經(jīng)指定了三個單獨的命令帶有-e選項。

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

執(zhí)行上面的代碼,會得到如下結(jié)果:

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

首先,創(chuàng)建一個包含在一個單獨的行的文本commands.txt文件,每次一行為每個sed命令,如下圖所示:

1d 
2d 
5d 

現(xiàn)在,我們可以指示sed從文本文件中讀取指令和執(zhí)行操作。這里,我們實現(xiàn)相同的結(jié)果,如圖在上述的例子。

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

執(zhí)行上面的代碼,會得到如下結(jié)果:

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 選項

這是模式緩沖區(qū)的缺省打印選項。 GNU sed解釋器提供--quiet,--silent選項作為 -n選項的替代。

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

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

-e 選項

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

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

執(zhí)行上面的代碼,會得到如下結(jié)果:

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

執(zhí)行上面的代碼,會得到如下結(jié)果:

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

上一篇:Sed實用功能下一篇:Sed模式范圍