1. sed編輯器基礎
1.1 替換標記
命令格式:s/pattern/replacement/flags
$ cat data4.txt
This is a test of the test script.
This is the second test of the test script.
有4種可用的替換標記:
數字,表明新文本將替換第幾處模式匹配的地方;
g,表明新文本將會替換所有匹配的文本;
p,表明原先行的內容要打印出來;
w file,將替換的結果寫到文件中。
在第一類替換中,可以指定sed編輯器用新文本替換第幾處模式匹配的地方。
??? $ sed 's/test/trial/2' data4.txt
?? This is a test of the trial script.
???? This is the second test of the trial script
將替換標記指定為2的結果就是: sed編輯器只替換每行中第二次出現的匹配模式。
g替換標記使你能替換文本中匹配模式所匹配的每處地方。
$ sed 's/test/trial/g' data4.txt
??????????????????????? This is a trial of the trial script.
??????????????????????? This is the second trial of the trial script.
????????????? p替換標記會打印與替換命令中指定的模式匹配的行。這通常會和sed的-n選項一起使用。
$ cat data5.txt
This is a test line.
This is a different line.
$
$ sed -n 's/test/trial/p' data5.txt
This is a trial line.
???????????? -n選項將禁止sed編輯器輸出。但p替換標記會輸出修改過的行。將二者配合使用的效果就是只輸出被替換命令修改過的行。
? w替換標記會產生同樣的輸出,不過會將輸出保存到指定文件中。
$ sed 's/test/trial/w test.txt' data5.txt
This is a trial line.
This is a different line.
$
$ cat test.txt
This is a trial line.
1.2 使用地址
在sed編輯器中有兩種形式的行尋址:
以數字形式表示行區間
以文本模式來過濾出行
1.3 刪除行
命令d執行刪除操作。
可以結合指定行號或是使用模式匹配。
通過特殊的文件結尾字符:
$ sed '3,$d' data6.txt
This is line number 1.
This is line number 2.
$
sed編輯器的模式匹配特性也適用于刪除命令。
$ sed '/number 1/d' data6.txt
This is line number 2.
This is line number 3.
This is line number 4.
$
說明 記住, sed編輯器不會修改原始文件。你刪除的行只是從sed編輯器的輸出中消失了。原始文件仍然包含那些“刪掉的”行
1.4 插入和附加文本
sed編輯器允許向數據流插入和附加文本行。
插入(insert)命令(i)會在指定行前增加一個新行;
附加(append)命令(a)會在指定行后增加一個新行。
命令行格式如下:
sed '[address]command\ new line'
例如:$ echo "Test Line 2" | sed 'i\Test Line 1'
Test Line 1
Test Line 2
$
1.5 轉換命令
轉換(transform)命令(y)是唯一可以處理單個字符的sed編輯器命令。轉換命令格式如下。
[address]y/inchars/outchars/
這里有個使用轉換命令的簡單例子。
$ sed 'y/123/789/' data8.txt
This is line number 7.
This is line number 8.
This is line number 9.
This is line number 4.
This is line number 7 again.
This is yet another line.
This is the last line in the file.
?
?
?
?
?