Linux中,除了VI這種交互式的文本編輯器(interactive text editor),還有兩個(gè)命令行文本編輯器(command line editor)徘公,就是sed和gawk竣贪,本文介紹sed命令。
sed
sed是stream editor玫荣,流編輯器甚淡。其處理流程:
- 每次從輸入流中讀取一行數(shù)據(jù)
- 將數(shù)據(jù)交給指定的命令處理
- 根據(jù)命令改變數(shù)據(jù)
- 將數(shù)據(jù)輸出到STDOUT
當(dāng)一行數(shù)據(jù)處理完成,就讀取下一行數(shù)據(jù)重復(fù)這個(gè)過(guò)程捅厂,直到所有的數(shù)據(jù)處理完成贯卦。
sed命令語(yǔ)法:
sed options script file
options參數(shù)有:
Option | Description |
---|---|
-e script | 使用指定的多個(gè)命令來(lái)處理數(shù)據(jù) |
-f file | 使用指定文件中的命令來(lái)處理數(shù)據(jù) |
-n | 不產(chǎn)生輸出,直到使用print命令 |
script參數(shù)只能指定一個(gè)命令焙贷,如果需要多個(gè)命令需要使用-e
option撵割,或者使用-f
option。
使用一個(gè)命令
sed默認(rèn)處理STDIN輸入流中的數(shù)據(jù)辙芍,所以可以使用管道(pipe):
$ echo "This is a test" | sed 's/test/big test/'
This is a big test
s
命令(substitute):文件替換啡彬,使用big test替換test,注意三個(gè)斜線故硅。
處理指定文件
$ 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不修改原文件內(nèi)容庶灿,只是將處理的結(jié)果發(fā)送到STDOUT,所以data1.txt的內(nèi)容不會(huì)改變吃衅。
使用多個(gè)命令
使用-e
option來(lái)指定多個(gè)命令往踢。
$ 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.
多個(gè)命令之前要用分號(hào)間隔開(kāi),并且分號(hào)前不能有空格
除了使用分號(hào)徘层,還可以使用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.
當(dāng)輸入了第一個(gè)單引號(hào)后峻呕,bash會(huì)開(kāi)啟secondary prompt,直到出現(xiàn)第二個(gè)單引號(hào)惑灵,當(dāng)出現(xiàn)第二個(gè)單引號(hào)山上,必須輸入后續(xù)完整的命令參數(shù),因?yàn)樵撔薪Y(jié)束英支,bash就會(huì)執(zhí)行命令佩憾。
從文件中讀取命令
如果有很多的sed命令,可以將命令寫在文件中,然后使用-f
option來(lái)指定該文件妄帘。
$ 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使用的命令所在文件的后綴標(biāo)識(shí)為.sed楞黄,方便識(shí)別。另外抡驼,命令不需要使用分號(hào)間隔鬼廓,每個(gè)命令一行即可。
參考:Linux Command Line and Shell Scripting Bible 3rd Edition 第19章