linux 系统 grep 命令
1、利用vim编辑器创建测试文件
[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
2、提取特定行
最简单的用法,提取包含特定字符串的行,例如提取包含字符串k的行:
[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep 'k' a.txt
s y k m
e t k r
加-n 参数,在匹配的行前面加上行号,例如提取包含k的行并加上行号:
[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep -n 'k' a.txt
2:s y k m
5:e t k r
-v 参数用反向匹配,提取不包含特定字符串的行,例如提取不包含k的行:
[root@linuxprobe test]# cat a.txt e d 4 9 s y k m 2 r t s w d g h e t k r [root@linuxprobe test]# grep -v 'k' a.txt e d 4 9 2 r t s w d g h
加^符号用于提取以特定字符开头的行,例如提取以e开头的行:
[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep '^e' a.txt
e d 4 9
e t k r
加$符号用于提取以特定字符串结尾的行,例如提取以s结尾的行:
[root@linuxprobe test]# cat a.txt
e d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep 's$' a.txt
2 r t s
加 -i参数用于忽略大小写:
[root@linuxprobe test]# cat a.txt
E d 4 9
s y k m
2 r t s
w d g h
e t k r
[root@linuxprobe test]# grep 'e' a.txt
e t k r
[root@linuxprobe test]# grep -i 'e' a.txt
E d 4 9
e t k r
加 \< 提取任意字符以特定字符开头的行,例如提取以f开头的行:
[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep '\<f' a.txt
s fafs k m
w fdsfd d g h
加 \> 提取任意字符以特定字符结尾的行,例如提取以r结尾的行:
[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep 'r\>' a.txt
2 sfr t s
e trdgt k r
-c 用于统计包含特定字符串的所有行数,(不是重复个数),例如出现s的所有行数:
[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep -c 's' a.txt
3
-o参数,用于统计出现特定字符串的所有次数,例如出现s的所有次数:
[root@linuxprobe test]# cat a.txt
E d 4 9
s fafs k m
2 sfr t s
w fdsfd d g h
e trdgt k r
[root@linuxprobe test]# grep -o 's' a.txt
s
s
s
s
s
[root@linuxprobe test]# grep -o 's' a.txt | wc -l
5
-w用于精确匹配,例如提取含有ab的行:
[root@linuxprobe test]# cat a.txt
E d 4 9
s abcde k m
2 ab t s
w abxy d g
e tr k r
[root@linuxprobe test]# grep 'ab' a.txt
s abcde k m
2 ab t s
w abxy d g
[root@linuxprobe test]# grep -w 'ab' a.txt
2 ab t s
-E参数,用于同时提取包含一个字符串以上的行,例如同时提取包含k和包含t的行:
[root@linuxprobe test]# cat a.txt
y d 4 9
s e k m
2 b t s
w a d g
e t k r
[root@linuxprobe test]# grep -E 'k|t' a.txt
s e k m
2 b t s
e t k r
分类:
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 绘制太阳,地球,月球 运作规律