Linux中,除了VI這種交互式的文本編輯器(interactive text editor),還有兩個命令行文本編輯器(command line editor),就是sed和gawk,本文介紹sed命令。
sed
sed是stream editor,流編輯器。其處理流程:
- 每次從輸入流中讀取一行數據
- 將數據交給指定的命令處理
- 根據命令改變數據
- 將數據輸出到STDOUT
當一行數據處理完成,就讀取下一行數據重復這個過程,直到所有的數據處理完成。
sed命令語法:
sed options script file
options參數有:
Option | Description |
---|---|
-e script | 使用指定的多個命令來處理數據 |
-f file | 使用指定文件中的命令來處理數據 |
-n | 不產生輸出,直到使用print命令 |
script參數只能指定一個命令,如果需要多個命令需要使用-e
option,或者使用-f
option。
使用一個命令
sed默認處理STDIN輸入流中的數據,所以可以使用管道(pipe):
$ echo "This is a test" | sed 's/test/big test/'
This is a big test
s
命令(substitute):文件替換,使用big test替換test,注意三個斜線。
處理指定文件
$ cat data1.txt
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
$ sed 's/dog/cat/' data1.txt
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
sed不修改原文件內容,只是將處理的結果發送到STDOUT,所以data1.txt的內容不會改變。
使用多個命令
使用-e
option來指定多個命令。
$ sed -e 's/brown/green/; s/dog/cat/' data1.txt
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
多個命令之前要用分號間隔開,并且分號前不能有空格
除了使用分號,還可以使用secondary prompt:
$ sed -e '
> s/brown/green/
> s/fox/elephant/
> s/dog/cat/' data1.txt
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
當輸入了第一個單引號后,bash會開啟secondary prompt,直到出現第二個單引號,當出現第二個單引號,必須輸入后續完整的命令參數,因為該行結束,bash就會執行命令。
從文件中讀取命令
如果有很多的sed命令,可以將命令寫在文件中,然后使用-f
option來指定該文件。
$ cat script1.sed
s/brown/green/
s/fox/elephant/
s/dog/cat/
$ sed -f script1.sed data1.txt
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
將sed使用的命令所在文件的后綴標識為.sed,方便識別。另外,命令不需要使用分號間隔,每個命令一行即可。
參考:Linux Command Line and Shell Scripting Bible 3rd Edition 第19章