shell脚本工具之sed命令

本文深入探讨了sed作为批处理流编辑器的高效特性,通过实例展示了如何仅显示匹配的行、直接修改文件内容、使用脚本进行文件处理、进行多项编辑、在文件中追加内容、替换匹配的内容、删除文件内容以及打印文件中的内容。此外,还演示了如何将匹配的内容保存到另一个文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     sed就是批处理的流编辑器,可以对来自文件或标准输入的输入流进行转换,sed通常被用作管道中的过滤器.由于sed仅仅对其输入进行一遍扫描,因此比其它交互式编辑器更加高效.

 

文件内容:

[root@tong1 opt]# cat sed.txt
1
tong
2
cheng
3
Hellow
4
Word
wu han
2 4 5
JD
Tao Bao

[root@tong1 opt]#

 

常用参数:

-n              --只输出匹配的行

-e              --多项编辑

-f               --使用脚本对文件处理

-i               --直接修改文件内容

-r              --在脚本中使用扩展正则表达式

 

1.只显示匹配的行

[root@tong1 opt]# sed -n '2p' sed.txt
tong

[root@tong1 opt]# sed -n '/^J/,$p' sed.txt      --以J开头到结尾输出
JD
Tao Bao

[root@tong1 opt]#

 

2.直接修改文件内容

[root@tong1 opt]# sed -i '/3/c 3.00' sed.txt
[root@tong1 opt]# grep '3.00' sed.txt
3.00
[root@tong1 opt]#

 

3.使用脚本名对文件处理

[root@tong1 opt]# cat 1.sh
#!/bin/sed -f
3,5p

[root@tong1 opt]# sed -n -f 1.sh  sed.txt
2
cheng
3.00
[root@tong1 opt]#

 

4.对文件多项编辑

[root@tong1 opt]# sed -n -e '2p' -e '4p' sed.txt
tong
cheng
[root@tong1 opt]#

 

常用命令:

a         --在匹配字符后新增

c         --替换

d         --删除

i          --插入

p         --打印.通常与参数 sed -n 一起用
s         --取代.通常这个 s 的动作可以搭配正则表达式。例如 1,20s/old/new/g

 

5.在文件中追加内容

[root@tong1 opt]# sed '/2/a\1111111111' sed.txt
1
tong
2
1111111111
cheng
3.00
Hellow
4
Word
wu han
2
1111111111
JD
Tao Bao

[root@tong1 opt]#

 

6.替换匹配的内容

[root@tong1 opt]# sed '/2/c\1111111111' sed.txt
1
tong
1111111111
cheng
3.00
Hellow
4
Word
wu han
1111111111
JD
Tao Bao

[root@tong1 opt]#

 

7.删除文件的内容

[root@tong1 opt]# sed '3,10d' sed.txt
1
tong
JD
Tao Bao

[root@tong1 opt]#

 

8.打印文件中的内容

[root@tong1 opt]# sed -n '3,4p' sed.txt
2
cheng

[root@tong1 opt]# sed -n '/2/,5p' sed.txt
2
cheng
3.00
2
[root@tong1 opt]#

 

9.将匹配的内容保存到另一个文件中

[root@tong1 opt]# sed -n '3,4 w  2.txt' sed.txt
[root@tong1 opt]# cat 2.txt
2
cheng
[root@tong1 opt]#

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值