替换命令在替换多行中的文本时能正常工作,但默认情况下它只替换每行中出现的第一处。要让替换命令能够替换一行中不同地方出现的文本必须使用替换标记(substitution flag)。替换标记会在替换命令字符串之后设置。
s/pattern/replacement/flags
有4种可用的替换标记:
- 数字,表明新文本将替换第几处模式匹配的地方;
- g,表明新文本将会替换所有匹配的文本;
- p,表明原先行的内容要打印出来;
- w file,将替换的结果写到文件中。
在第一类替换中,可以指定sed编辑器用新文本替换第几处模式匹配的地方。
$ sed 's/test/trial/2' data.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' data.txt
This is a trial of the trial script.
This is the second trial of the trial script.
$
p替换标记会打印与替换命令中指定的模式匹配的行。这通常会和sed的-n选项一起使用。
$ cat data.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' data.txt
This is a trial line.
This is a different line.
$
$ cat test.txt
This is a trial line.
$
sed编辑器的正常输出是在STDOUT中,而只有那些包含匹配模式的行才会保存在指定的输出文件中。