linux系统中sed命令提取指定的行
1、测试数据如下:
[root@centos79 test]# seq 10 > a.txt [root@centos79 test]# ls a.txt [root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10
2、提取第2行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '2p' a.txt 2
3、提取第2行到第7行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '2,7p' a.txt 2 3 4 5 6 7
4、只提取第2行和第7行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '2p;7p' a.txt 2 7
5、提取奇数行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '1~2p' a.txt 1 3 5 7 9
6、提取偶数行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '2~2p' a.txt 2 4 6 8 10
7、提取3倍数行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '3~3p' a.txt 3 6 9
利用正则表达式提取特定行。
8、测试数据如下:
[root@centos79 test]# seq 15 > a.txt [root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
9、提取匹配2的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/2/p' a.txt 2 12
10、提取没有匹配2的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/2/!p' a.txt 1 3 4 5 6 7 8 9 10 11 13 14 15
11、提取同时匹配2和5的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/2\|5/p' a.txt 2 5 12 15
12、提取没有匹配2或者5的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/2\|5/!p' a.txt 1 3 4 6 7 8 9 10 11 13 14
13、提取以2开头的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/^2/p' a.txt 2
13、提取以2结尾的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/2$/p' a.txt 2 12
14、同时提取以2开头或者以5开头的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/^2\|^5/p' a.txt 2 5
15、同时提取以2和5结尾的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@centos79 test]# sed -n '/2$\|5$/p' a.txt 2 5 12 15
16、提取以1开头以5结尾的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 13340 213435 1332425 13 1434 13245 [root@centos79 test]# sed -n '/^1.*5$/p' a.txt 1332425 13245
17、提取3的倍数行以外的行
[root@centos79 test]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@centos79 test]# sed -n '3~3!p' a.txt 1 2 4 5 7 8 10
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律