随笔20-Linux探索(三剑客之sed)

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 擅长列操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值