grep
grep
命令如何使用?grep
命令的常见用法?
简介
grep
命令用于搜索文本。它在给定文件中搜索包含与给定字符串或单词匹配的行。它是 Linux 和类 Unix 系统中最有用的命令之一。让我们看看如何在 Linux 或类 Unix 系统上使用 grep
。
grep
命令是一个包含 grep
、egrep
和 fgrep
命令的大家族,都用于搜索文本。
常见用法
下面是一些标准的 grep
命令,通过示例说明了如何在Linux、macOS和Unix上使用 grep
:
(1)在文件 foo.txt 中搜索单词 word
grep 'word' foo.txt
(2)在文件 foo.txt 中搜索单词 word,并且忽略大小写
grep -i 'word' foo.txt
上述命令会把位于 foo.txt
文件中的 WORD
、Word
、word
等忽略大小写的 word
全部搜索出来。
(3)在当前目录以及所有子目录中查找单词 word
grep -R 'word' .
注意:最后面有一个点,代表当前目录。
-r
命令也是递归搜索,只是-r
不会搜索符号链接文件。
(4)搜索并显示单词 word 出现的次数
grep -c 'word' foo.txt
(5)只匹配单词 word
grep -w 'word' foo.txt
这意味着 fooword
、word123
等单词不会被搜索出来,而只会将 a word
这种类型的 word
搜索出来。
(6)搜索单词 word1 或 word2
egrep -w 'word1|word2' foo.txt
(7)结果显示行号
grep -n 'root' /etc/passwd
(8)反匹配搜索
grep -v word foo.txt
foo.txt 文件中,不包含 word
的行,会被搜索出来。
(9)显示匹配行的上下文
当展示结果行的时候,顺便将 word
所在行的前面 3 行,也显示出来:
grep -B 3 'word' foo.txt
将 word
所在航的后 4 行,显示出来:
grep -A 4 'word' foo.txt
使用 -C
命令同时展示出前 3 行和后 4 行:
grep -C 3 'word' foo.txt
(10)与其它 Shell 命令结合
显示 CPU 型号:
cat /proc/cpuinfo | grep -i 'Model'
(11)仅显示匹配的文件名
grep -l 'main' *.c
(12)搜索结果高亮显示
grep --color vivek /etc/passwd
(13)搜索多个文件
grep word *.txt
(14)排除/引入某些文件
只在 rootdir
文件夹内的 *.cpp
和 *.h
文件中搜索 abc
这个关键字:
grep 'abc' -r --include="*.{cpp,h}" rootdir
# 或
grep 'abc' -r --include=*.cpp --include=*.h rootdir
在当前文件夹,只搜索 *.js
文件,但是排除 *js/lib/*
路径和 *.min.js
这些文件:
grep "z-index" . --include=*.js --exclude=*js/lib/* --exclude=*.min.js
排除多个模式,比如 --exclude=pattern1 --exlucde=pattern2
,可以使用 {}
把多个 pattern
包括起来:
--exclude={pattern1,pattern2,pattern3}
正则表达式
grep
支持三种类型的正则表达式语法:
- basic (BRE)
- extended (ERE)
- perl (PCRE)
(1)匹配行的开头
grep ^vivek /etc/passwd
vivek 仅作为行的开头的时候,才会被搜索出来。
(2)匹配行结尾
grep 'foo$' filename
foo 仅作为行的结尾的时候,才会被搜索出来。
(3)点需要被转义
在 grep
中,.
有特殊含义,它可以匹配任何字符,所以如果需要匹配 .
,那么需要使用反斜杠 \
对其进行转义:
grep '192\.168\.1\.254' hosts
(4)搜索多个字符串
grep -E 'word1|word2' filename
# 或
egrep 'word1|word2' filename
(5)搜索带有横杠的字符串
grep -e '--test--' filename
如果不加
-e
选项,那么--test
将会按照grep
命令的参数–test–
来处理
参考
- How To Use grep Command In Linux / UNIX
- Regular expressions in grep ( regex ) with examples
- Use grep –exclude/–include syntax to not grep through certain files
扫描下面二维码,在手机端阅读: