grep使用常用操作十五条

(21) 2024-03-06 12:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说grep使用常用操作十五条,希望能够帮助你!!!。

grep的全部使用语法参照grep --help
构造数据如下:test001.txt与test002.txt

grep使用常用操作十五条_https://bianchenghao6.com/blog__第1张

 日常工作常用的语法如下:

 

一、在单个文件中查询指定字符串

grep abc test01/test01.txt

查看结果如下:

grep使用常用操作十五条_https://bianchenghao6.com/blog__第2张

 

二、在多个文件中查找指定字符串(并支持问文件通配符)

grep -i cdE ./*/*

grep使用常用操作十五条_https://bianchenghao6.com/blog__第3张

 

三、过滤多个关键字:“与”和“或”(cat+管道+grep实现)

cat test01/test01.txt | grep ab |grep cd #同时包含ab与cd

grep使用常用操作十五条_https://bianchenghao6.com/blog__第4张

cat test01/test01.txt | grep -E "ab|cd" #包含ab或cd

grep使用常用操作十五条_https://bianchenghao6.com/blog__第5张

 

四、查找的过程中忽略大小写(grep -i)

grep -i abcd */*

grep使用常用操作十五条_https://bianchenghao6.com/blog__第6张

 

五、匹配完整的单词,而不是子串(grep -w)

grep -w ab */*

grep使用常用操作十五条_https://bianchenghao6.com/blog__第7张

 

六、高亮grep的显示结果(grep --color=auto)

alias grep='grep --color=auto'

查看alias快捷命令是否已经添加过grep的高亮显示设置,否则添加以上的快捷指令 或直接带颜色查询

grep --color=auto abc test01/test01.txt

grep使用常用操作十五条_https://bianchenghao6.com/blog__第8张

 

七、使用 -r 参数来实现递归的搜索目录(grep -r)

不使用递归时只能查询指令的目录下的文件,使用递归时可以逐层查询

grep -r abc ./*

grep使用常用操作十五条_https://bianchenghao6.com/blog__第9张

 

八、取反搜索结果(grep -v)

grep -v abc test01/test01.txt

grep使用常用操作十五条_https://bianchenghao6.com/blog__第10张

 

九、取反(多个)指定模式的匹配结果

grep -v -e ab -e cd test01/test01.txt 

grep使用常用操作十五条_https://bianchenghao6.com/blog__第11张

 

十、只显示匹配命中的文件名称,而不显示具体匹配的内容(grep -l)

grep -l abc test01/test01.txt

grep使用常用操作十五条_https://bianchenghao6.com/blog__第12张

 

十一、显示匹配的字符串位置。该位置是相对于整个文件的字节位置,不是行数(grep -b)

grep -b abc test01/test01.txt

grep使用常用操作十五条_https://bianchenghao6.com/blog__第13张

 

十二、显示匹配的字符串在文件中的行数(grep -n)

grep -n abc test01/test01.txt

grep使用常用操作十五条_https://bianchenghao6.com/blog__第14张

十三、显示所匹配行的前后行信息(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行

grep使用常用操作十五条_https://bianchenghao6.com/blog__第15张

 

十四、正则匹配以x开头(以y结尾)的字符

grep "^a" test01/test01.txt #以a开头 grep "^a..d$" test01/test01.txt #以a开头以d结尾,中间两个字符

grep使用常用操作十五条_https://bianchenghao6.com/blog__第16张

 

 十五、统计复合结果条件的行数(grep -c)

grep -c ab test01/test01.txt

grep使用常用操作十五条_https://bianchenghao6.com/blog__第17张

 

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复