grep使用常用操作十五条
grep的全部使用语法参照grep --help
构造数据如下:test001.txt与test002.txt
日常工作常用的语法如下:
一、在单个文件中查询指定字符串
grep abc test01/test01.txt
查看结果如下:
二、在多个文件中查找指定字符串(并支持问文件通配符)
grep -i cdE ./*/*
三、过滤多个关键字:“与”和“或”(cat+管道+grep实现)
cat test01/test01.txt | grep ab |grep cd #同时包含ab与cd
cat test01/test01.txt | grep -E "ab|cd" #包含ab或cd
四、查找的过程中忽略大小写(grep -i)
grep -i abcd */*
五、匹配完整的单词,而不是子串(grep -w)
grep -w ab */*
六、高亮grep的显示结果(grep --color=auto)
alias grep='grep --color=auto'
查看alias快捷命令是否已经添加过grep的高亮显示设置,否则添加以上的快捷指令 或直接带颜色查询
grep --color=auto abc test01/test01.txt
七、使用 -r 参数来实现递归的搜索目录(grep -r)
不使用递归时只能查询指令的目录下的文件,使用递归时可以逐层查询
grep -r abc ./*
八、取反搜索结果(grep -v)
grep -v abc test01/test01.txt
九、取反(多个)指定模式的匹配结果
grep -v -e ab -e cd test01/test01.txt
十、只显示匹配命中的文件名称,而不显示具体匹配的内容(grep -l)
grep -l abc test01/test01.txt
十一、显示匹配的字符串位置。该位置是相对于整个文件的字节位置,不是行数(grep -b)
grep -b abc test01/test01.txt
十二、显示匹配的字符串在文件中的行数(grep -n)
grep -n abc test01/test01.txt
十三、显示所匹配行的前后行信息(grep -A(after),grep -B(before),grep -C(可省略after+before))
grep -nw -A2 abcd test01/test01.txt #-A之后n行
grep -nw -B2 abcd test01/test01.txt #-B之前n行
grep -nw -C2 abcd test01/test01.txt #-C前后n行
grep -nw -2 abcd test01/test01.txt #-C省略前后n行
十四、正则匹配以x开头(以y结尾)的字符
grep "^a" test01/test01.txt #以a开头
grep "^a..d$" test01/test01.txt #以a开头以d结尾,中间两个字符
十五、统计复合结果条件的行数(grep -c)
grep -c ab test01/test01.txt
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了