Linux文本搜索工具grep使用详解

jopen 9年前

一、grep (缩写来自Globally search a Regular Expression and Print)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。Unix的grep家族包括grep、egrep和fgrep

grep: 默认支持基本正则表达式;
egrep: 扩展正则表达式;
fgrep: 不支持正则表达式元字符,搜索字符串的速度快

二、通过man手册获取grep帮助信息:

#man grep

GREP(1)                                                                GREP(1)

NAME
grep, egrep, fgrep – print lines matching a pattern

SYNOPSIS
grep [options] PATTERN [FILE...]
grep [options] [-e PATTERN | -f FILE] [FILE...]

DESCRIPTION
Grep  searches  the  named input FILEs (or standard input if no files are named, or the file name – is given) for
lines containing a match to the given PATTERN.  By default, grep prints the matching lines.

In addition, two variant programs egrep and fgrep are available.  Egrep is the same as  grep -E.   Fgrep  is  the
same as grep -F.

三、grep的常用选项

–color=auto
export GREP_COLOR=’01;36′
-v: 反向选取,只显示不符合模式的行;
-o: 只显示被模式匹配到的字串,而不是整个行;
-i: 不区分字符大小写;
-A #:显示匹配到的行时,顺带显示其后面的#个行;
-A 2
-B #:前面的#行;
-C #:前后的#行;

-E: 使用扩展的正则表达式
grep -E = egrep

三、grep正则表达式基本元字符集

元字符:不表示字符本身的意义,而用于额外功能性的描述

^:锚定行首的符合条件的内容

# grep “^root” /etc/passwd //搜索以root开头的行

Linux文本搜索工具grep使用详解

$: 锚定行尾的符合条件的内容

#grep “bash$” /etc/passwd //搜索以bash结尾的行

Linux文本搜索工具grep使用详解

.: 匹配任意单个字符

Linux文本搜索工具grep使用详解

匹配s和l之间有单个任意字符的内容

Linux文本搜索工具grep使用详解

*:匹配紧挨在其前面的字符任意次(包含0次)

Linux文本搜索工具grep使用详解

匹配k前面有0个或任意个s

Linux文本搜索工具grep使用详解

[]:匹配指定范围内的任意单个字符

匹配D或d中间包含两个任意字符并以n结尾的行

Linux文本搜索工具grep使用详解
[^]:匹配指定范围外的任意单个字符

Linux文本搜索工具grep使用详解

#grep “[^A-Z].*a” text –color=auto  //匹配任意一个非大与字母后面面跟0个或多个任意字符以a结尾的行

Linux文本搜索工具grep使用详解
\?: 匹配紧挨在其前面的字符0次或1次;

匹配b之前有0个或1个a

Linux文本搜索工具grep使用详解

匹配a和b之前有0个或1个任意字符

Linux文本搜索工具grep使用详解

\{m,n\}: 匹配其前面的字符至少m次,至多n次;
            \{0,n\}: 至多n次;0-n次;
\{m,\}:至少m次
\{m\}: 精确匹配m次;

匹配b 前面的a 至少1次至多2次

Linux文本搜索工具grep使用详解

\<: 锚定词首,用法格式:\<pattern
\b: \bpattern

搜索以root为词首的行

Linux文本搜索工具grep使用详解

  \>: 锚定词尾,用法格式:pattern\>
            \b: pattern\b

搜索以root为词尾的行

Linux文本搜索工具grep使用详解
\<pattern\>:锚定单词

搜索包含root单词的行

Linux文本搜索工具grep使用详解

\(\): 分组,用法格式: \(pattern\)

\1  :可以引用第一个分组匹配到的内容
\2  :可以引用第二个分组匹配到的内容
搜索R或r和d之间出现两个任意字符而后又跟0个或多个任意字符 ,并在其后引用匹配到的内容

Linux文本搜索工具grep使用详解

字符集合

[:digit:] 所有数字 0-9

[:lower:] 所有小写字母  a-z

[:upper:] 所有大写字母 A-Z

[:punct:] 所有标点符号

[:space:] 表示空格或tab键

[:alpha:] 表示所有字母(包含大小写)a-zA-Z

[:alnum:] 表示所有字母和数字  a-zA-Z0-9

注:非需要这样表示[^[] ], 如[[:space :]]表示空格 [^[:space:]] 表示非空

搜索/boot/grub/grub.conf 以空格开头的行

Linux文本搜索工具grep使用详解

来源:haidongqing07 的BLOG