您的位置:首页 > 运维架构 > Shell

【Shell】【学习笔记】Linux Shell脚本应用(十一)

2014-10-25 09:55 666 查看
课时11 sed文本处理工具

一、sed基本用法
sed流式编辑器/文本过滤
Stream Editor
基于模式匹配过滤/修改文本
注:与awk相比,sed可以改变原有文本中的内容。

二、基本命令格式
语法格式:
sed'编辑指令序列' 文件1 文件2 ......
sed -n '编辑指令序列'
文件1 文件2 ......
sed -i '编辑指令序列'
文件1 文件2 ......
例如:sed -n '3,5p' /etc/hosts
编辑指令的写法:
格式:[行地址1[,行地址2]]操作类型
多条指令之间以分号隔开
例如:sed -n '3p;5p' /etc/hosts

最常用的操作类型

p
输出/打印文本行
n
取下一行文本(跳过当前行)
d
删除
s
字符串替换
a
追加新的文本
二、输出文本

准备测试文件:file.txt
[root@localhost ~]# cat file.txt
1 This is the first line.
2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
4 hunter:x:504:504::/home/hunter:/bin/bash

示例1:按行号输出文本
[root@localhost ~]# sed -n 'p;n' file.txt //输出所有奇数行

1 This is the first line.
3 192.168.4.2 w2k8.benet.com

[root@localhost ~]# sed -n 'n;p' file.txt //输出所有偶数行

2 Hello, Everybody!
4 hunter:x:504:504::/home/hunter:/bin/bash

示例2:使用正则表达式
[root@localhost ~]# sed -n '/w2k8/,$p' file.txt //输出从第一个包含w2k8的行开始到文件最后

3 192.168.4.2 w2k8.benet.com
4 hunter:x:504:504::/home/hunter:/bin/bash

[root@localhost ~]# sed -n '/\<This\>/p' file.txt //输出包含单词This的行
1 This is the first line.

三、删除及替换文本

示例3:删除符合条件的行
[root@localhost ~]# sed '2,3d' file.txt //删除第二行到第三行

1 This is the first line.
4 hunter:x:504:504::/home/hunter:/bin/bash

[root@localhost ~]# sed '/w2k8/d;$d' file.txt //输出包含w2k8的行和最后一行

1 This is the first line.
2 Hello, Everybody!

示例4:删除不符合条件的行
[root@localhost ~]# sed '/ne/!d' file.txt //删除不包含字符串ne的行

1 This is the first line.
3 192.168.4.2 w2k8.benet.com

示例5:替换符合条件的文本
[root@localhost ~]# sed '3,4s/hunter/BADBOY/g' file.txt //将第三行到第四行中的hunter替换成BADBOY

1 This is the first line.
2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
4 BADBOY:x:504:504::/home/hunter:/bin/bash

示例6:使用替换操作进行插入、删除
[root@localhost ~]# sed '1,2s/^/#/g' file.txt //在第一行到第二行的行首插入#

#1 This is the first line.
#2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
4 BADBOY:x:504:504::/home/hunter:/bin/bash

[root@localhost ~]# sed 's/ter//g' file.txt //删除字符串ter(替换为空)

#1 This is the first line.
#2 Hello, Everybody!
3 192.168.4.2 w2k8.benet.com
4 BADBOY:x:504:504::/home/hun:/bin/bash
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: