简介
grep (global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。
Unix的grep家族包括grep、egrep和fgrep。egrep和fgrep的命令只跟grep有很小不同。egrep是grep的扩展,支持更多的re元字符, fgrep就是fixed grep或fast grep,它们把所有的字母都看作单词,也就是说,正则表达式中的元字符表示回其自身的字面意义,不再特殊。linux使用GNU版本的grep。它功能更强,可以通过-G、-E、-F命令行选项来使用egrep和fgrep的功能。
grep常用用法
grep [-acinv] [--color=auto] '搜寻字符串' filename
选项与参数:
-a :将 binary 文件以 text 文件的方式搜寻数据
-c :计算找到 '搜寻字符串' 的次数
-i :忽略大小写的不同,所以大小写视为相同
-n :顺便输出行号
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!
--color=auto :可以将找到的关键词部分加上颜色的显示喔!
示例:
1. 将/etc/passwd,有出现 root 的行取出来
# grep root /etc/passwd
# cat /etc/passwd | grep root
2. 将/etc/passwd,有出现 root 的行取出来,同时显示这些行在/etc/passwd的行号
# grep -n root /etc/passwd
在关键字的显示方面,grep 可以使用 --color=auto 来将关键字部分使用颜色显示。 用alias使用别名,就不用每次都加入了。在 ~/.bashrc 内加上这行:『alias grep='grep --color=auto'』再以『 source ~/.bashrc 』来立即生效!
3. 将/etc/passwd,将没有出现 root 的行取出来
# grep -v root /etc/passwd
4. 将/etc/passwd,将没有出现 root 和nologin的行取出来
# grep -v root /etc/passwd | grep -v nologin
5.用 dmesg 列出核心信息,再以 grep 找出内含 eth 那行,要将捉到的关键字显色,且加上行号来表示:
# dmesg | grep -n --color=auto 'eth'
6. 根据文件内容递归查找目录
# grep ‘energywise’ * #在当前目录搜索带'energywise'行的文件
# grep -r ‘energywise’ * #在当前目录及其子目录下搜索'energywise'行的文件
# grep -l -r ‘energywise’ * #在当前目录及其子目录下搜索'energywise'行的文件,但是不显示匹配的行,只显示匹配的文件
这几个命令很使用,是查找文件的利器。
7. grep与正规表达式
# grep -n 't[ae]st' regular_express.txt
其实 [] 里面不论有几个字节,他都谨代表某『一个』字节, 所以,上面的例子说明了,我需要的字串是『tast』或『test』两个字串而已!
字符类的反向选择 [^] :如果想要搜索到有 oo 的行,但不想要 oo 前面有 g,如下
# grep -n '[^g]oo' regular_express.txt
# grep -n '[^a-z]oo' regular_express.txt
# grep -n '[0-9]' regular_express.txt
# grep -n '^the' regular_express.txt
# grep -n '^[a-z]' regular_express.txt
# grep -n '^[^a-zA-Z]' regular_express.txt
^ 符号,在字符类符号(括号[])之内与之外是不同的! 在 [] 内代表『反向选择』,在 [] 之外则代表定位在行首的意义!
# grep -n '\.$' regular_express.txt
# 找出空白行:只有行首跟行尾 (^$)
# grep -n '^$' regular_express.txt
. (小数点):代表『一定有一个任意字节』的意思;
* (星号):代表『重复前一个字符, 0 到无穷多次』的意思,为组合形态
假设我需要找出 g??d 的字串,亦即共有四个字节, 起头是 g 而结束是 d ,我可以这样做:
8. 扩展grep(grep -E 或者 egrep):
使用扩展grep的主要好处是增加了额外的正则表达式元字符集。
打印所有包含NW或EA的行。如果不是使用egrep,而是grep,将不会有结果查出。
# egrep 'NW|EA' testfile
对于标准grep,如果在扩展元字符前面加\,grep会自动启用扩展选项-E。
#grep 'NW\|EA' testfile
搜索所有包含一个或多个3的行。
# egrep '3+' testfile
# grep -E '3+' testfile
# grep '3\+' testfile
搜索所有包含0个或1个小数点字符的行。
# egrep '2\.?[0-9]' testfile
# grep -E '2\.?[0-9]' testfile
# grep '2\.\?[0-9]' testfile
#首先含有2字符,其后紧跟着0个或1个点,后面再是0和9之间的数字。
搜索一个或者多个连续的no的行。
# egrep '(no)+' testfile
# grep -E '(no)+' testfile
# grep '\(no\)\+' testfile #3个命令返回相同结果,
不使用正则表达式
fgrep 查询速度比grep命令快,但是不够灵活:它只能找固定的文本,而不是规则表达式。
如果你想在一个文件或者输出中找到包含星号字符的行
fgrep '*' /etc/profile
for i in /etc/profile.d/*.sh ; do
或
grep -F '*' /etc/profile
for i in /etc/profile.d/*.sh ; do