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编辑器中有两种形式的行寻址:
以数字形式表示行区间
以文本模式来过滤出行