1 . 简介
sed 可以取各种内容,比较擅长行操作, 是三剑客的老二
[root@localhost file]# touch sed.txt
[root@localhost file]# echo "This is the first line">>sed.txt
[root@localhost file]# echo "This is the second line">>sed.txt
[root@localhost file]# echo "This is the third line">>sed.txt
2.选项参数
-n: 取消原始输出
# p 表示打印 n 表示取消原始输出
[root@localhost file]# sed -n /second/p sed.txt
This is the second line
[root@localhost file]#
[root@localhost file]# sed /^second/p sed.txt
This is the first line
This is the second line
This is the third line
[root@localhost file]#
# p 表示打印 n 表示取消原始输出 d 表示删除
[root@localhost file]# sed -n /second/d sed.txt
This is the first line
This is the third line
[root@localhost file]#
3.案例演示
3.1 先生成一个很多行的文本文件
[root@localhost command]# seq 100 >seq.txt
[root@localhost command]# cat seq.txt | wc -l # 统计行数
100
[root@localhost command]#
3.2 完成需求 (读取文本中21 - 30行数据)
(1) sed 实现
# 采用 sed 读取21 - 30行 # 打印21 - 30 行数据
[root@localhost command]# sed -n 21,30p seq.txt
21
22
23
24
25
26
27
28
29
30
[root@localhost command]#
(2) awk 实现
# 打印 21 - 30 行数据
[root@localhost command]# awk '{if(NR>20&&NR<31) print $0 }' seq.txt
21
22
23
24
25
26
27
28
29
30
(3) 采用其他方式实现
# 采用其他方式读取 21 - 30行
[root@localhost command]# tail -80 seq.txt | head -10 # 只打印21 - 30 行数据
21
22
23
24
25
26
27
28
29
30
[root@localhost command]#
3.2 打印文本中第30 行数据
# 打印第30 行数据
[root@localhost command]# sed -n 30p seq.txt
30
3.3 打印时字符串替换(不改变原有文件内容)
[root@localhost file]# cat happy.text
I hope you can keep a good mood every day, and I also wish you can enjoy your every day!
You are welcome ! Windows
[root@localhost file]# sed s#Windows#Linux#g happy.text
I hope you can keep a good mood every day, and I also wish you can enjoy your every day!
You are welcome ! Linux
Note:
对于awk 和 sed 来说: sed 擅长行,awk 擅长列操作