Linux sed命令

本文梳理一下平时用到过的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、替换的新字符串后一定要加"/",即使不全局替换也要加,否则会报错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值