Content #
替换标志在替换命令字符串之后设置。
s/pattern/replacement/flags
有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(global)可以替换文本行中所有的匹配文本: $ 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. $ sed编辑器的正常输出会被保存在STDOUT中,只有那些包含匹配模式的行才会被保存在指定的输出文件中。
From #
Linux命令行与shell脚本编程大全