Rootop 服务器运维与web架构

sed替换、添加行


# 源文件
[root@localhost ~]# cat 111
that's venus file
dont edit it
by venus

# 替换字符串
[root@localhost ~]# sed -i 's/venus/simon/' 111
[root@localhost ~]# cat 111
that's simon file
dont edit it
by simon
可以看到venus都被替换为simon

# 字符串中包含单引号的替换
[root@localhost ~]# cat 111
that's simon file
dont edit it
by simon

sed中的单引号需要换成双引号
[root@localhost ~]# sed -i "s/that's/aaa/" 111
[root@localhost ~]# cat 111
aaa simon file
dont edit it
by simon

# 字符串中包含双引号的替换
[root@localhost ~]# cat 111
that"s simon file
dont edit it
by simon

[root@localhost ~]# sed -i 's/that"s/aaa/' 111
[root@localhost ~]# cat 111
aaa simon file
dont edit it
by simon


# 对于带$符号的替换
[root@localhost ~]# cat 111
name=venus
that's $name file
dont edit it
by simon

[root@localhost ~]# sed -i 's/$name/aaa/' 111
[root@localhost ~]# cat 111
name=venus
that's aaa file
dont edit it
by simon
不需要转义

# 插入 行下面
[root@localhost ~]# cat 111
a
b
c
在a下面插入eee字符串
[root@localhost ~]# sed -i '/a/a\eee' 111
[root@localhost ~]# cat 111
a
eee
b
c

# 在a上面插入fff字符串
[root@localhost ~]# cat 111
a
eee
b
c
abc
eee

[root@localhost ~]# sed -i '/a/i\fff' 111
[root@localhost ~]# cat 111
fff
a
eee
b
c
fff
abc
eee


# 插入有特殊字符的
[root@localhost ~]# cat 111
a
b
c
[root@localhost ~]# sed -i '/a/a\hello world \\' 111
[root@localhost ~]# cat 111
a
hello world \
b
c
就需要转义特殊字符


# 插入带换行的字符串
[root@localhost ~]# cat 111
a
b
c
[root@localhost ~]# sed -i '/b/a\hello world \\\nhello world2' 111
[root@localhost ~]# cat 111
a
b
hello world \
hello world2
c
通过\n来换行

原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/3589.html

作者:Venus

服务器运维与性能优化

评论已关闭。