一:
Sed的使用方式主要参考下面的格式:
[address][command]/pattern/replacement/flag
address是指运用于那些行,如果不特别指出的话就是运用到所有的行
command是具体的要如何操作的命令。主要有以下几个命令
a:新增, a的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
c:取代, c的后面可以接字串,这些字串可以取代 n1,n2之间的行!
d:删除,因为是删除啊,所以 d后面通常不接任何咚咚;
i:插入, i的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
p:列印,亦即将某个选择的数据印出。通常 p会与参数 sed -n一起运行~
s:取代,可以直接进行取代的工作哩!通常这个s的动作可以搭配正规表示法!
/pattern/replacement:其中pattern是正则表达式中的pattern是一个意思,就是找到要对其进行操作的字符。Replacement就是要替换的字符
Flag:是修饰替换的标识。有下面几个作用:
n:1到512之间的一个数字,表示对文本模式中指定模式第n次出现的情况进行替换
g:全局更改
p:打印模式空间的内容
w:将模式空间的内容写到文件中去
下面我们来看下具体的使用:
假设我有这样的一篇文档:
This is a linuxsed/awk test file,the operate system is linux
linux is a operate system that can doanything
我想将其中的linux换成windows. 其中包含3个linux词语。首先建立prj1.sed文件。其中脚本为:s/linux/windows/
我们来看下运行的结果:
可以看到第一行的第一个linux以及第二行的linux都被替换成了windows。但是第一行的第二个linux并没有被替换。证明这个命令只涉及每一行中出现的第一个pattern,其他的pattern都没有涉及.
$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
windows is a operate system that can doanything
如果想替换所有的pattern,脚本改为s/linux/windows/g.可以看到结果就符合预期了。其中g的作用在于替换每行中所有符合的pattern
$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
windows is a operate system that can doanything
再继续修改脚本:/This/s/linux/windows/g。添加了地址信息。也就是只有在包含This的行才会被应用替换命令。下面的结果可以看到只有第一行的信息被替换了
$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
linux is a operate system that can do anything
我们还可以指定具体的行范围。比如1,2 s/linux/windows/g。这里表明就是将1-2行的字符进行替换:
$ sed -fprj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
windows is a operate system that can doanything
如果我们只是想替换第一行第二次出现的linux字符,该如何操作呢。这里就要用到flag修饰符了。脚本修改为:/This/s/linux/windows/2
$ sed -fprj1.sed prj1.txt
This is a linux sed/awk test file,the operate system is windows
linux is a operate system that can do anything
最后来看下flag中p的作用,这个其实就是将符合模式的哪一行内容重新打印了出来
/This/s/linux/windows/p。这里可以看到多出来一行。就是p的打印
$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,the operate system is linux
This is a windows sed/awk test file,the operate system is linux
linux is a operate system that can do anything