一、概念
grep(Global search Regular Expression and Print out the line)强大的文本搜索工具,从文本文件或管道数据流中筛选匹配的行及数据,并把匹配的行/特定内容打印出来。

二、grep命令格式

grep [参数] [匹配模式] [查找的文件]

1、参数:

举例演示说明:

[root@PCS101 ~]# cat testgrep
zsy test
zsythink www.zsythink.com
TEST
Zsy's articles
grep Grep
abc
abc123abc
123zsy123

(1)-i,–ignore-case:忽略Pattern 和文件内容的大小写,默认情况下,grep是区分大小写的.

[root@PCS101 ~]# grep "test" testgrep
zsy test
[root@PCS101 ~]# grep -i "test" testgrep
zsy test
TEST

(2)-o:只打印匹配到的关键字,如果一行有多处匹配到也会分行来打印
-n –line-number 显示行号

[root@PCS101 ~]# grep -i "" testgrep
TEST
abc123abc
123zsy123
[root@PCS101 ~]# grep -i -n -o "" testgrep
:
:
:
:
[root@PCS101 ~]# grep -i -n "test" testgrep
:zsy test
:TEST

(3)-c 打印匹配到的总行数

[root@PCS101 ~]# grep -i -c "test" testgrep

(4)--color=auto 很有用,你看的出来

[root@PCS101 ~]# grep -i -n --color "test" testgrep
:zsy test
:TEST

(5)-Bn:输出匹配行之前的n行;-An:输出匹配行之后的n行;-Cn输出匹配行前后各n行

[root@PCS101 ~]# grep -B2 "www" testgrep
zsythink www.zsythink.com
[root@PCS101 ~]# grep -A3 "www" testgrep
www.zsythink.com
TEST
Zsy's articles
grep Grep
[root@PCS101 ~]# grep -C3 "www" testgrep
zsy test
zsythink www.zsythink.com
TEST
Zsy's articles
grep Grep

(6)-w –word-regexp:只选择匹配上整个单词时输出

[root@PCS101 ~]# grep "zsy" testgrep
zsy test
zsythink
www.zsythink.com
123zsy123
[root@PCS101 ~]# grep -w "zsy" testgrep
zsy test

(7)-v –invert-match:取没有匹配的行

[root@PCS101 ~]# grep -v "zsy" testgrep

TEST
Zsy's articles
grep Grep
abc
abc123abc

(8)-e:根据不同的匹配模式来匹配

[root@PCS101 ~]# grep -e "abc" -e "test" testgrep
zsy test
abc
abc123abc

(9)-q:静默模式 当只关心某文件是否含有某个字符时 不关心匹配的行,需要使用echo $?输出0表示匹配到;输出1表示未匹配到

[root@PCS101 ~]# grep -q "test" testgrep
[root@PCS101 ~]# echo $? [root@PCS101 ~]# grep -q "ttttttt" testgrep
[root@PCS101 ~]# echo $?

(10)用grep -r递归搜索全部的文件
如果想查找当前目前以及其子目录的全部文件时,可以使用 -r 选项。如下例

[root@PCS101 ~]# grep -r "abc def" *
ddd/t1.txt:abc def hij klm
pcre-8.40/testdata/testoutput4: abc def\x{}\x{}xyz\npqr
pcre-8.40/testdata/testoutput4: abc def\x{}\x{}xyz\npqr
pcre-8.40/testdata/testinput4: abc def\x{}\x{}xyz\npqr
pcre-8.40/testdata/testinput4: abc def\x{}\x{}xyz\npqr

(11)用grep -l 只显示符合匹配条件的文件名

[root@PCS101 ddd]# grep -l "abc def" *
t1.txt

(12)grep默认使用基本正则表达式

egrep表示支持扩展正则表达式,相当于 grep -E;
grep -P 表示支持perl兼容的正则表达式;
fgrep表示不支持正则表达式,只能匹配写死的正则表达式,但是效率快;

2、匹配模式
匹配模式是你要好找的东西,可以是普通的文字符号也可以是正则表达式。

(1)扩展正则表达式在基本正则表达式上进行了修改,主要取消反斜线转移,更容易看

字符匹配:
.: 任意单个字符
[]: 指定范围内的任意单个字符
[^]: 指定范围外的任意单个字符 次数匹配:
*:匹配其前面的字符任意次;
?: 匹配其前面的字符0或1次;
+: 匹配其前面的字符至少1次
{m}: 匹配其前面的字符m次;
{m,n}: 至少m次,至多n次
{m,}: 至少m次;
{,n}:至多n次; 锚定:
^: 行首
$: 行尾
\<, \b: 词首
\>, \b:词尾 分组:
(): 分组
|: 或者, ac|bc
grep -E "con(C|c)at" 匹配conCat或concat

(2)基本正则表达式

匹配次数
*:前一个字符出现任意次数,包括0次
.* :任意字符出现任意次数
\?:前一个字符出现1次或者0次
\+:出现1次或者1次以上
\{n\}:精确匹配次数
\{m,n\}:匹配m到n次之间
\{n,\} :匹配最少n次以上
\{,n\} :匹配最多n次以上
[a-z]\+ : 任意一个字符至少出现一次 ;
. 在[]中没有任何意义,就是点本身 位置锚定
^ : 匹配行首
$ ; 匹配行尾
^$: 匹配空白行
[^]:取反匹配 分组
\(匹配内容\) :匹配括号内的内容
\n (数字) :重复前面匹配的内容再匹配

参考:

正则表达式应用案例

04-17 07:58