shell脚本工具之sed命令

简介:

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

 

文件内容:

[root@tong1 opt]# cat sed.txt 
1
tong

cheng

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]#










本文转自 z597011036 51CTO博客,原文链接:http://blog.51cto.com/tongcheng/1623351,如需转载请自行联系原作者
目录
相关文章
|
6月前
|
关系型数据库 MySQL Shell
MySQL 备份 Shell 脚本:支持远程同步与阿里云 OSS 备份
一款自动化 MySQL 备份 Shell 脚本,支持本地存储、远程服务器同步(SSH+rsync)、阿里云 OSS 备份,并自动清理过期备份。适用于数据库管理员和开发者,帮助确保数据安全。
|
4月前
|
存储 Unix Shell
确定Shell脚本在操作系统中的具体位置方法。
这对于掌握Linux的文件系统组织结构和路径方面的理解很有帮助,是我们日常工作和学习中都可能使用到的知识。以上讲解详细清晰,应用简便,是每一个想要精通操作系统的计算机爱好者必备的实用技能。
97 17
|
4月前
|
Linux Shell
Centos或Linux编写一键式Shell脚本删除用户、组指导手册
Centos或Linux编写一键式Shell脚本删除用户、组指导手册
113 4
|
4月前
|
Linux Shell 数据安全/隐私保护
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
250 3
|
5月前
|
Linux Shell
在Linux、CentOS7中设置shell脚本开机自启动服务
以上就是在CentOS 7中设置shell脚本开机自启动服务的全部步骤。希望这个指南能帮助你更好地管理你的Linux系统。
378 25
|
5月前
|
存储 Unix Shell
Shell 输出命令完全指南:echo 与 printf 的深度剖析
本文深入解析了 Shell 编程中 `echo` 和 `printf` 两个核心输出命令的用法与区别。`echo` 简单易用,适合基础输出;`printf` 功能强大,支持复杂格式化。文章从语法、转义序列、高级技巧到实际应用场景(如日志记录、进度显示)逐一讲解,并对比两者的性能与适用场景,帮助开发者根据需求灵活选择。最后通过进阶技巧和常见问题解答,进一步提升对两者的掌握程度。
257 1
|
Linux Shell Windows
4:Bash shell命令-步入Linux的现代方法
4:Bash shell命令-步入Linux的现代方法
196 0
|
Shell 数据处理 Python
Python 运行 shell 命令的一些方法
Python 运行 shell 命令的一些方法
112 0
|
Shell 数据处理 Python
Python 运行 shell 命令的一些方法
Python 运行 shell 命令的一些方法