[root@www ~]# sed [-nefr] [动作]
选项与参数:s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!
以上内容转载自:linux sed命令详解,文章写得很好
以下说说个人的理解与一些例子。
用来举例的文件内容如下:
root@ubuntu:/opt# nl learnSed.txt
aaaaa
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
sed以行为单位进行操作,所以说,如果你指定行号,那么命令只会对指定的行生效。
比如说:root@ubuntu:/opt# sed '1ahahahah.txt' learnSed.txt
aaaaa
hahahah.txt
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
如果不指定行号:
root@ubuntu:/opt# sed 'ahahahah.txt' learnSed.txt
aaaaa
hahahah.txt
bbbbb
hahahah.txt
ccccc
hahahah.txt
ddddd
hahahah.txt
eeeee
hahahah.txt
/a/b/c/d/e.txt
hahahah.txt
fffff
hahahah.txt
hahahah.txx
连空行后面都被插入了内容。而且注意的是命令a与后面的内容并不需要分隔符
s命令也是同样:
root@ubuntu:/opt# sed 's/aaa/bbb/' learnSed.txt
bbbaa
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
第一行的aaa被替换掉了,而如果指定行号为2,第1行的内容不会被替换掉
root@ubuntu:/opt# sed '2s/aaa/bbb/' learnSed.txt
aaaaa
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
root@ubuntu:/opt# sed '/aaa/ahahahah.txt' learnSed.txt
aaaaa
hahahah.txt
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
可以用反斜杆来指定其他分隔符
root@ubuntu:/opt# sed '\#aaa#ahahahah.txt' learnSed.txt
aaaaa
hahahah.txt
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
命令a后面的空格会被忽略:
root@ubuntu:/opt# sed '\#aaa#a hahahah.txt' learnSed.txt
aaaaa
hahahah.txt
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
还是用反斜杆,可以不忽略空格
root@ubuntu:/opt# sed '\#aaa#a\ hahahah.txt' learnSed.txt
aaaaa
hahahah.txt
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
当然,s命令也可以用搜索来指定行,不指定行的执行结果如下:
root@ubuntu:/opt# sed 's/a/bbb/' learnSed.txt
bbbaaaa
bbbbb
ccccc
ddddd
eeeee
/bbb/b/c/d/e.txt
fffff
root@ubuntu:/opt#
用搜索指定行的执行结果:
root@ubuntu:/opt# sed '/aaaaa/s/a/bbb/' learnSed.txt
bbbaaaa
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
注意到第一行只替换了一个a,可以用g指定全局替换:
root@ubuntu:/opt# sed '/aaaaa/s/a/bbb/g' learnSed.txt
bbbbbbbbbbbbbbb
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
s命令不指定行时指定分隔符的语法
root@ubuntu:/opt# sed 's#aaa#bbb#' learnSed.txt
bbbaa
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff
当然,也可以有这种蠢一点的写法^_^:
root@ubuntu:/opt# sed '\#.*#s#aaa#bbb#' learnSed.txt
bbbaa
bbbbb
ccccc
ddddd
eeeee
/a/b/c/d/e.txt
fffff