课时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:使用正则表达式
3 192.168.4.2 w2k8.benet.com
4 hunter:x:504:504::/home/hunter:/bin/bash
1 This is the first line.
三、删除及替换文本
示例3:删除符合条件的行
1 This is the first line.
4 hunter:x:504:504::/home/hunter:/bin/bash
1 This is the first line.
2 Hello, Everybody!
示例4:删除不符合条件的行
1 This is the first line.
3 192.168.4.2 w2k8.benet.com
示例5:替换符合条件的文本
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:使用替换操作进行插入、删除
#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
#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