Linux实用细节命令3,sed非交互式流式编辑器增删改查

img

sed参数

  • -n:不打印全文内容
  • -i:修改原始文件
  • -r:支持扩展正则表达式

Example

num终端命令语意
1sed -n ‘3p’ /etc/passwd打印第3行
2sed -n ‘1,3p’ /etc/passwd打印第1至3行
3sed -n ‘1~2p’ /etc/passwd打印第1开始步长为2的行
4sed -n ‘1,+2p’ /etc/passwd打印第一行和后2行
5sed -n ‘/^root/p’ /etc/passwd打印正则过滤root开头
6sed -nr ‘/[0-9]{3}/p’ /etc/passwd打印三个数字的行

p:print

num终端命令语意
1sed ‘/IPADDR/p’ /etc/sysconfig/network-script/ifcg-eth0打印网络地址信息
2free | sed -n ‘/Mem/p’过滤内存信息
3sed -n ‘//$/p’打印第1开始步长为2的行
4df -h |sed -n ‘1,+2p’ /etc/passwd过滤磁盘根分区
5sed -n ‘/2p;3p,10p/p’ /etc/passwd打印多行
6sed -nr ‘/2!/p’ /etc/passwd打印三个数字的行

d:delete

num终端命令语意
1sed -i ‘d’ ./rubbish.txt删除文件
2sed -i '1,3d’ /tmp/*删除文件
3sed -i ‘/dev/!d’不包含dev的行都删除
4df -h |sed -i '/^#/d /etc/passwd删除以#开头的行
5sed -i ‘/^$/d’ /etc/passwd删除空白行

c:replace

num终端命令语意
1sed ‘c 123456’ /etc/sysconfig/network-script/ifcg-eth0所有行都换成123456
2sed ‘/IPADDR/c IPADDR=192.168.1.3’替换网卡信息
3sed ‘/127/c 127.0.0.1’ /tmp/ipaddress.txt替换127这行为127.0.0.1
4sed ‘/4c XXXX’ /tmp/ipaddress.txt替换第4行为XXXX

s:substution

num终端命令语意
1sed ‘s/1024/2048/’ ./tmp/test.txt替换每一行第1个出现
2sed ‘s/1024/2048/g’ ./tmp/test.txt替换每一行的全部
3sed ‘s/1024/2048/2’ ./tmp/test.txt替换每一行第2个出现
4sed ‘s/1024/($)/g’ ./tmp/test.txt替换每一行1024为(1024)
5sed ‘2s/1024/2048/g’ ./tmp/test.txt替换第2行的全部
6sed ‘2s/1024//g’ ./tmp/test.txt第2行的1024删除掉
7sed -n ‘2s/1024/2048/p’ ./tmp/test.txt替换完成后打印第2行
8sed ‘s#1024#2048#g’ ./tmp/test.txt替换符改为#
9sed ‘s!1024!2048!2’ ./tmp/test.txt替换符改为!
10sed ‘s2\10242\20482\2’ ./tmp/test.txt替换符改为2,但是要加\
11echo “123456” | sed -r ‘s/^(.)(.*)(.)$/\3\2\1/’正则符号()具有保留的功能

=:打印行号

num终端命令语意
1sed -n ‘8=’ /etc/passwd打印第8行行号
2sed -n ‘/root/=’ /etc/passwd打印有root行的行号
3sed -n ‘$=’ /etc/passwd统计行数
3wc -l /etc/passwd统计行数

i:insert

num终端命令语意
1sed ‘2i ABC_123’ /etc/passwd插入到第二行之前
2sed ‘/1024/i ABC\n2048’ /etc/passwd插入到每一个匹配则前

a:append

num终端命令语意
1sed ‘2a ABC_123’ /etc/passwd追加到第二行之后
2sed ‘/1024/a ABC\n2048’ /etc/passwd追加到每一个匹配则后

r:read

num终端命令语意
1sed ‘2r ,/cont.txt’ ./dest.txt读取cont.txt追加到des.txt第2行
2sed ‘/1024/r ,/cont.txt’ ./dest.txt’ /etc/passwd

w:write

num终端命令语意
1sed ‘w ,/cont.txt’ ./dest.txt另存dest.txt 为/cont.txt
2sed ‘2,3w ,/cont.txt’ ./dest.txt ’另存dest.txt 的2,3行为/cont.txt
3sed ‘/1024/w ,/cont.txt’ ./dest.txt ’另存dest.txt 的匹配行为/cont.txt
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

屯门山鸡叫我小鸡

加油

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值