sed 字符串替换
作者:互联网
content
macname@localhost Desktop % macname@localhost Desktop % cat ddd This is a test of the test script. This is the second test of the test script. macname@localhost Desktop %
#在行中替换文本
macname@localhost Desktop % sed 's/test/trial/' ddd This is a trial of the test script. This is the second trial of the test script. macname@localhost Desktop %
#指定sed编辑器用新文本替换第几处模式匹配的地方
macname@localhost Desktop % macname@localhost Desktop % sed 's/test/trial/2' ddd This is a test of the trial script. This is the second test of the trial script. macname@localhost Desktop %
将替换标记指定为2的结果就是:sed编辑器只替换每行中第二次出现的匹配模式。
g替换标 记使你能替换文本中匹配模式所匹配的每处地方
macname@localhost Desktop % macname@localhost Desktop % sed 's/test/trial/g' ddd This is a trial of the trial script. This is the second trial of the trial script. macname@localhost Desktop %
p替换标记会打印与替换命令中指定的模式匹配的行。这通常会和sed的-n选项一起使用。
-n选项将禁止sed编辑器输出。但p替换标记会输出修改过的行。将二者配合使用的效果就是 只输出被替换命令修改过的行
macname@localhost Desktop % cat ddd This is a test of the test script. This is the second test of the test script. Dededede Hahahahhahahaah macname@localhost Desktop % macname@localhost Desktop % sed -n 's/test/trial/p' ddd This is a trial of the test script. This is the second trial of the test script. macname@localhost Desktop %
w替换标记会产生同样的输出,不过会将输出保存到指定文件中
macname@localhost Desktop % cat ddd This is a test of the test script. This is the second test of the test script. Dededede Hahahahhahahaah macname@localhost Desktop % sed 's/test/trial/w test.txt' ddd This is a trial of the test script. This is the second trial of the test script. Dededede Hahahahhahahaah macname@localhost Desktop % cat test.txt This is a trial of the test script. This is the second trial of the test script. macname@localhost Desktop %
sed编辑器允许选择其他字符来作为替换命令中的字符串分隔符,这里感叹号被用作字符串分隔符
macname@localhost Desktop % cat ddd This is a test of the test script. This is the second test of the test script. Dededede Hahahahhahahaah macname@localhost Desktop % macname@localhost Desktop % sed -n 's!test!trial!p' ddd This is a trial of the test script. This is the second trial of the test script. macname@localhost Desktop %
在这个例子中,感叹号被用作字符串分隔符,这样路径名就更容易阅读和理解了。
macname@localhost Desktop % macname@localhost Desktop % sed 's!/bin/bash!/bin/csh!' /etc/passwd
标签:script,trial,macname,test,sed,字符串,Desktop,替换,localhost 来源: https://www.cnblogs.com/sea-stream/p/14067623.html