sed编辑器基础之替换命令(二)

来源:互联网 发布:早期电脑网络打枪游戏 编辑:程序博客网 时间:2024/06/03 05:41

sed根据模式替换的命令格式是这样的:

s/pattern/replacement/flags

其中flags可以写数字,数字是多少,就是第几个位置:

我们还是看栗子吧。

首先新建一个文件名为data的文本作为数据范例:

test test testtest test

当flags没有指定的时候:

$ sed 's/test/trail/' datatrail test testtrail test

好,结果出来了,看到没,当flags没指定的时候,替换的是每行第一处匹配的地方,其他的都没动。

再看,假设flags=2:

$ sed 's/test/trail/2' datatest trail testtest trail

这次的结果是第二个匹配的地方陪替换掉了,这时候你大概已经能猜到了,flag等于多少,意思就是第几处匹配的地方被替换,这个猜想是正确的。当然如果你心里没底,那就再往下试试……,看看等于3的时候是啥情况:

$ sed 's/test/trail/3' datatest test trailtest test

flags=4

$ sed 's/test/trail/4' datatest test testtest test

经过验证,猜想是正确的,其实它确实也是这么干的。看个边界情况吧,让flags=0试试会输出啥:

$ sed 's/test/trail/0' datased: -e expression #1, char 14: number option to `s' command may not be zero

报错了,看来s命令是不支持0的。

经过上述试验,我们可得出以下结论:

  • 没有指定flags的值的时候,flags默认为1;
  • flags不能为0,因为s命令不支持;
  • 当flags在有效的范围内,那就替换其相应的位置;
  • 当flags指定的位置超出范围,那就不做替换操作。

还是比较简单的,很容易理解。

相信大家很可能更关心这个问题,如果要全部替换咋办,全部替换也简单,让flags=g就行了,看示例:

$ sed 's/test/trail/g' datatrail trail trailtrail trail

flags还可以设为p,p的意思就是将替换过的行打印出来,注意,这里没有说没替换就不打印了

文本data里的东西换一下吧:

This is the first line.This is the second line.This is the third line.

换好后执行以下:

$ sed 's/first/replacement/p' dataThis is the replacement line.This is the replacement line.This is the second line.This is the third line.

哦,全部打印出来了啊,就是比以前多打印了一行,这时候新的需求来了:只打印发生替换操作的行,咋办?好办,sed的-n参数帮你搞定。

$ sed -n 's/first/replacement/p' dataThis is the replacement line.

这不就符合需求了嘛!

最后flags还可以等于w,这个w意思就是可以将替换的结果写到文本里。

$ sed 's/first/replacement/w text' dataThis is the replacement line.This is the second line.This is the third line.l$ cat textThis is the replacement line.
0 0
原创粉丝点击