本文梳理一下平时用到过的sed命令
1、在有某内容的行前或行后添加内容
#在内容行的后一行添加新增内容
sed -i '/文件内容/a\新增内容' test.txt
#在内容行的前一行添加新增内容
sed -i '/文件内容/i\新增内容' test.txt
a:append(附加),在某行后附加上一行
i:insert(插入),在某行前插入一行
例子:
#查看test.txt内容
[root@localhost ~]# cat test.txt
qwe
asdf
zxc
asdf
#在包含'qwe'内容的行前新增一行内容'123'
[root@localhost ~]# sed -i '/qwe/i\123' test.txt
#查看test.txt内容
[root@localhost ~]# cat test.txt
123
qwe
asdf
zxc
asdf
#在包含'asd'内容的行前新增一行内容'456'
[root@localhost ~]# sed -i '/asd/a\456' test.txt
#查看test.txt内容
[root@localhost ~]# cat test.txt
123
qwe
asdf
456
zxc
asdf
456
2、在某一行前或行后添加内容
# 在某一行前添加内容
sed -i 行数i\添加内容 filename
# 在某一行后添加内容
sed -i 行数a\添加内容 filename
例子:
#查看test.txt内容
[root@localhost ~]# cat test.txt
qwe
asdf
zxc
asdf
#第一行新增一行内容'123'
[root@localhost ~]# sed -i '1i\123' test.txt
#查看test.txt内容
[root@localhost ~]# cat test.txt
123
qwe
asdf
zxc
asdf
#第一行行后新增一行内容'456'
[root@localhost ~]# sed -i '1a\456' test.txt
#查看test.txt内容
[root@localhost ~]# cat test.txt
123
456
qwe
asdf
zxc
asdf
3、替换内容
#替换test.sh文件第n行内容asd为qwe
sed -i 'ns/asd/qwe/' test.sh
#替换test.sh文件每行第一次出现的asd为qwe 注意是每行的第一次出现
sed -i 's/asd/qwe/' test.sh
#替换test.sh文件全局的asd为qwe
sed -i 's/asd/qwe/g' test.sh
例子:
#查看test.txt内容
[root@localhost ~]# cat test.txt
qweqwe
asdf
zxc
asdf
#第2行的asd替换为qwe
[root@localhost ~]# sed -i '2s/asd/qwe/' test.txt
qweqwe
qwef
zxc
asdf
#每一行第一次出现的qwe替换为zxc 这里不改变文件
[root@localhost ~]# sed 's/qwe/zxc/' test.txt
zxcqwe
zxcf
zxc
asdf
#全局替换
[root@localhost ~]# sed 's/qwe/zxc/g' test.txt
zxczxc
zxcf
zxc
asdf
ps:
1、g是对每行的全局内容进行匹配 如果是ns/qwe/zxc/g 则表示对第n行的全部qwe替换为zxc 其他行不替换
2、替换的新字符串后一定要加"/",即使不全局替换也要加,否则会报错