>  기사  >  php教程  >  linux grep 명령에 대한 자세한 설명

linux grep 명령에 대한 자세한 설명

高洛峰
高洛峰원래의
2016-12-13 14:13:231218검색

소개

grep(전역 검색 정규식(RE) 및 줄 인쇄, 정규식 종합 검색 및 줄 인쇄)은 정규식을 사용할 수 있는 강력한 텍스트 검색 도구입니다. 일치하는 줄을 인쇄합니다.

유닉스의 grep 계열에는 grep, egrep, fgrep이 있습니다. egrep 및 fgrep 명령은 grep과 약간만 다릅니다. egrep은 더 많은 메타 문자를 지원하는 grep의 확장입니다. fgrep은 모든 문자를 단어로 처리하는 고정 grep입니다. 즉, 정규 표현식의 메타 문자는 더 이상 특별하지 않은 문자 그대로의 의미를 나타냅니다. Linux는 GNU 버전의 grep을 사용합니다. 더욱 강력하며 -G, -E 및 -F 명령줄 옵션을 통해 egrep 및 fgrep 기능을 사용할 수 있습니다.

grep의 일반적인 사용법

[root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename
选项与参数:
-a :将 binary 文件以 text 文件的方式搜寻数据
-c :计算找到 '搜寻字符串' 的次数
-i :忽略大小写的不同,所以大小写视为相同
-n :顺便输出行号
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!
--color=auto :可以将找到的关键词部分加上颜色的显示喔!

/etc/passwd를 제거하고 루트가 있는 줄을 제거합니다.

# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
或
# cat /etc/passwd | grep root 
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

/etc/passwd를 제거합니다. , 루트가 나타나는 줄을 제거하고 /etc/passwd에 이 줄의 줄 번호를 표시합니다.

# grep -n root /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
30:operator:x:11:0:operator:/root:/sbin/nologin

키워드 표시 측면에서 grep은 --color=auto를 사용하여 키워드를 표시할 수 있습니다. 색상을 사용하여 표시됩니다. 이것은 매우 좋은 기능입니다! 하지만 grep을 사용할 때마다 --color=auto를 추가해야 한다면 매우 번거로울 것입니다~ 이때 유용한 별칭을 처리해야 합니다! ~/.bashrc에 "alias grep='grep --color=auto'" 줄을 추가한 다음 "source ~/.bashrc"를 추가하면 즉시 적용됩니다! 이런 식으로 grep을 실행할 때마다 자동으로 컬러 디스플레이가 추가됩니다.

/etc/passwd를 제거하고 루트가 표시되지 않는 줄을 제거합니다

# grep -v root /etc/passwdroot:x:0:0:
root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

/etc/passwd에서 root와 nologin이 나타나지 않는 행을 제거합니다

# grep -v root /etc/passwd | grep -v nologin
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

dmesg를 사용하여 핵심 정보를 나열한 다음 grep을 사용하여 eth가 포함된 행을 찾고 키워드를 캡처합니다. 색상을 지정하고 표시할 줄 번호를 추가합니다.

[root@www ~]# dmesg | grep -n --color=auto 'eth'
247:eth0: RealTek RTL8139 at 0xee846000, 00:90:cc:a6:34:84, IRQ 10
248:eth0: Identified 8139 chip type 'RTL-8139C'
294:eth0: link up, 100Mbps, full-duplex, lpa 0xC5E1
305:eth0: no IPv6 routers present
# 你会发现除了 eth 会有特殊颜色来表示之外,最前面还有行号喔!

키워드 표시 측면에서 grep은 --color=auto를 사용하여 키워드 부분을 색상으로 표시할 수 있습니다. 이것은 매우 좋은 기능입니다! 하지만 grep을 사용할 때마다 --color=auto를 추가해야 한다면 매우 번거로울 것입니다~ 이때 유용한 별칭을 처리해야 합니다! ~/.bashrc에 "alias grep='grep --color=auto'" 줄을 추가한 다음 "source ~/.bashrc"를 추가하면 즉시 적용됩니다! 이런 식으로 grep을 실행할 때마다 자동으로 컬러 디스플레이가 추가됩니다.

dmesg를 사용하여 핵심 정보를 나열한 다음 grep을 사용하여 eth가 포함된 줄을 찾습니다. 키워드가 위치한 줄 처음 2줄과 마지막 3줄도 함께 캡쳐하여 표시합니다

[root@www ~]# dmesg | grep -n -A3 -B2 --color=auto 'eth'
245-PCI: setting IRQ 10 as level-triggered
246-ACPI: PCI Interrupt 0000:00:0e.0[A] -> Link [LNKB] ...
247:eth0: RealTek RTL8139 at 0xee846000, 00:90:cc:a6:34:84, IRQ 10
248:eth0: Identified 8139 chip type 'RTL-8139C'
249-input: PC Speaker as /class/input/input2
250-ACPI: PCI Interrupt 0000:00:01.4[B] -> Link [LNKB] ...
251-hdb: ATAPI 48X DVD-ROM DVD-R-RAM CD-R/RW drive, 2048kB Cache, UDMA(66)
# 如上所示,你会发现关键字 247 所在的前两行及 248 后三行也都被显示出来!
# 这样可以让你将关键字前后数据捉出来进行分析啦!

파일 내용을 기준으로 디렉토리를 재귀적으로 검색합니다

# grep ‘energywise’ *           #在当前目录搜索带'energywise'行的文件

# grep -r ‘energywise’ *        #在当前目录及其子目录下搜索'energywise'行的文件
# grep -l -r ‘energywise’ *     #在当前目录及其子目录下搜索'energywise'行的文件,但是不显示匹配的行,只显示匹配的文件

이들은 명령은 매우 유용하며 파일을 찾는 데 강력한 도구입니다.

grep 및 정규 표현식

문자 클래스

문자 클래스 검색: test 또는 테이스트라는 두 단어를 검색하려면 다음과 같이 할 수 있습니다. 실제로는 공통된 't?st'가 있다는 것을 알아냈습니다~ 이때는 이렇게 검색할 수 있습니다.

[root@www ~]# grep -n 't[ae]st' regular_express.txt
8:I can't finish the test.
9:Oh! The soup taste good.

사실 [] 안에는 몇 바이트가 들어가더라도 특정을 나타냅니다. "1" 바이트이므로 위의 예에서는 필요한 문자열이 "tast" 또는 "test" 두 문자열임을 보여줍니다!

문자 클래스 역선택 [^]: oo가 있는 행을 검색하고 싶지만 oo 앞에 g가 오는 것을 원하지 않는 경우 다음과 같이

[root@www ~]# grep -n '[^g]oo' regular_express.txt
2:apple is my favorite food.
3:Football game is not use feet only.
18:google is the best tools for search keyword.
19:goooooogle yes!

foo와 Foo가 모두 허용되므로 2행과 3행에 대해서는 의심의 여지가 없습니다!

하지만 18번째 줄에는 "google"을 의미하는 "goo"라는 단어가 분명히 포함되어 있습니다. 이 줄 뒤에 "tool"을 의미하는 "too"라는 단어가 나타나기 때문에 잊지 마세요! 그래서 이 줄도 나열되어 있어요~ 즉, 18번 줄에 우리가 원하지 않는 항목(goo)이 나오긴 하지만, 필요한 항목도 있기 때문에 문자열 검색과 일치합니다!

19번째 줄도 마찬가지입니다. goooooogle의 oo 앞에 o가 올 수 있기 때문입니다(예: go(ooo)oogle). 따라서 이 줄도 요구 사항을 충족합니다!

문자 클래스의 연속: 다음으로 oo 앞에 소문자 바이트를 원하지 않기 때문에 [^abcd....z]oo를 이렇게 쓸 수 있다고 가정해 보겠습니다. 이는 ASCII에서 소문자 바이트의 인코딩 순서가 연속적이기 때문에 매우 편리하지 않은 것 같습니다. 따라서 다음과 같이 단순화할 수 있습니다.

[root@www ~]# grep -n '[^a-z]oo' regular_express.txt
3:Football game is not use feet only.

즉, 그룹에서 바이트를 수집할 때, 바이트 그룹은 영어 대문자/소문자 영어/숫자 등과 같이 연속적이므로 [a-z], [A-Z], [0-9] 등을 사용하여 쓸 수 있습니다. 그러면 요청 문자열이 숫자와 영어? 헤헤! 모두 함께 쓰면 [a-zA-Z0-9]가 됩니다.

다음과 같이 숫자가 포함된 행을 가져오고 싶습니다.

[root@www ~]# grep -n '[0-9]' regular_express.txt
5:However, this dress is about $ 3183 dollars.
15:You are the best is mean you are the no. 1.

行首与行尾字节 ^ $
行首字符:如果我想要让 the 只在行首列出呢? 这个时候就得要使用定位字节了!我们可以这样做:

[root@www ~]# grep -n '^the' regular_express.txt
12:the symbol '*' is represented as start.

此时,就只剩下第 12 行,因为只有第 12 行的行首是 the 开头啊~此外, 如果我想要开头是小写字节的那一行就列出呢?可以这样:

[root@www ~]# grep -n '^[a-z]' regular_express.txt
2:apple is my favorite food.
4:this dress doesn't fit me.
10:motorcycle is cheap than car.
12:the symbol '*' is represented as start.
18:google is the best tools for search keyword.
19:goooooogle yes!
20:go! go! Let's go.

如果我不想要开头是英文字母,则可以是这样:

[root@www ~]# grep -n '^[^a-zA-Z]' regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
21:# I am VBird

^ 符号,在字符类符号(括号[])之内与之外是不同的! 在 [] 内代表『反向选择』,在 [] 之外则代表定位在行首的意义!

 

那如果我想要找出来,行尾结束为小数点 (.) 的那一行:

[root@www ~]# grep -n '\.$' regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
4:this dress doesn't fit me.
10:motorcycle is cheap than car.
11:This window is clear.
12:the symbol '*' is represented as start.
15:You are the best is mean you are the no. 1.
16:The world <Happy> is the same with "glad".
17:I like dog.
18:google is the best tools for search keyword.
20:go! go! Let&#39;s go.

特别注意到,因为小数点具有其他意义(底下会介绍),所以必须要使用转义字符(\)来加以解除其特殊意义!

 

找出空白行:

[root@www ~]# grep -n &#39;^$&#39; regular_express.txt22:

因为只有行首跟行尾 (^$),所以,这样就可以找出空白行啦!

 

任意一个字节 . 与重复字节 *
这两个符号在正则表达式的意义如下:

. (小数点):代表『一定有一个任意字节』的意思;
* (星号):代表『重复前一个字符, 0 到无穷多次』的意思,为组合形态

假设我需要找出 g??d 的字串,亦即共有四个字节, 起头是 g 而结束是 d ,我可以这样做:

[root@www ~]# grep -n &#39;g..d&#39; regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
9:Oh! The soup taste good.
16:The world <Happy> is the same with "glad".

因为强调 g 与 d 之间一定要存在两个字节,因此,第 13 行的 god 与第 14 行的 gd 就不会被列出来啦!

 

如果我想要列出有 oo, ooo, oooo 等等的数据, 也就是说,至少要有两个(含) o 以上,该如何是好?

因为 * 代表的是『重复 0 个或多个前面的 RE 字符』的意义, 因此,『o*』代表的是:『拥有空字节或一个 o 以上的字节』,因此,『 grep -n 'o*' regular_express.txt 』将会把所有的数据都列印出来终端上!

当我们需要『至少两个 o 以上的字串』时,就需要 ooo* ,亦即是:

[root@www ~]# grep -n &#39;ooo*&#39; regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
9:Oh! The soup taste good.
18:google is the best tools for search keyword.
19:goooooogle yes!

如果我想要字串开头与结尾都是 g,但是两个 g 之间仅能存在至少一个 o ,亦即是 gog, goog, gooog.... 等等,那该如何?

[root@www ~]# grep -n &#39;goo*g&#39; regular_express.txt
18:google is the best tools for search keyword.
19:goooooogle yes!

如果我想要找出 g 开头与 g 结尾的行,当中的字符可有可无

[root@www ~]# grep -n &#39;g.*g&#39; regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
14:The gd software is a library for drafting programs.
18:google is the best tools for search keyword.
19:goooooogle yes!
20:go! go! Let&#39;s go.

因为是代表 g 开头与 g 结尾,中间任意字节均可接受,所以,第 1, 14, 20 行是可接受的喔! 这个 .* 的 RE 表示任意字符是很常见的.

 

如果我想要找出『任意数字』的行?因为仅有数字,所以就成为:

[root@www ~]# grep -n &#39;[0-9][0-9]*&#39; regular_express.txt
5:However, this dress is about $ 3183 dollars.
15:You are the best is mean you are the no. 1.

限定连续 RE 字符范围 {}
我们可以利用 . 与 RE 字符及 * 来配置 0 个到无限多个重复字节, 那如果我想要限制一个范围区间内的重复字节数呢?

举例来说,我想要找出两个到五个 o 的连续字串,该如何作?这时候就得要使用到限定范围的字符 {} 了。 但因为 { 与 } 的符号在 shell 是有特殊意义的,因此, 我们必须要使用字符   \ 来让他失去特殊意义才行。 至於 {} 的语法是这样的,假设我要找到两个 o 的字串,可以是:

[root@www ~]# grep -n &#39;o\{2\}&#39; regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
9:Oh! The soup taste good.
18:google is the best tools for search ke
19:goooooogle yes!

假设我们要找出 g 后面接 2 到 5 个 o ,然后再接一个 g 的字串,他会是这样:

[root@www ~]# grep -n &#39;go\{2,5\}g&#39; regular_express.txt
18:google is the best tools for search keyword.

如果我想要的是 2 个 o 以上的 goooo....g 呢?除了可以是 gooo*g ,也可以是:

[root@www ~]# grep -n &#39;go\{2,\}g&#39; regular_express.txt
18:google is the best tools for search keyword.
19:goooooogle yes!

扩展grep(grep -E 或者 egrep):
使用扩展grep的主要好处是增加了额外的正则表达式元字符集。

 

打印所有包含NW或EA的行。如果不是使用egrep,而是grep,将不会有结果查出。

    # egrep &#39;NW|EA&#39; testfile     
    northwest       NW      Charles Main        3.0     .98     3       34
    eastern         EA      TB Savage           4.4     .84     5       20

对于标准grep,如果在扩展元字符前面加\,grep会自动启用扩展选项-E。

#grep &#39;NW\|EA&#39; testfile
northwest       NW      Charles Main        3.0     .98     3       34
eastern         EA      TB Savage           4.4     .84     5       20

搜索所有包含一个或多个3的行。

# egrep &#39;3+&#39; testfile
# grep -E &#39;3+&#39; testfile
# grep &#39;3\+&#39; testfile        
#这3条命令将会
northwest       NW      Charles Main          3.0     .98     3       34
western         WE      Sharon Gray           5.3     .97     5       23
northeast       NE      AM Main Jr.           5.1     .94     3       13
central         CT      Ann Stephens          5.7     .94     5       13

搜索所有包含0个或1个小数点字符的行。

# egrep &#39;2\.?[0-9]&#39; testfile 
# grep -E &#39;2\.?[0-9]&#39; testfile
# grep &#39;2\.\?[0-9]&#39; testfile 
#首先含有2字符,其后紧跟着0个或1个点,后面再是0和9之间的数字。
western         WE       Sharon Gray          5.3     .97     5       23
southwest       SW      Lewis Dalsass         2.7     .8      2       18
eastern         EA       TB Savage             4.4     .84     5       20

搜索一个或者多个连续的no的行。

# egrep &#39;(no)+&#39; testfile
# grep -E &#39;(no)+&#39; testfile
# grep &#39;\(no\)\+&#39; testfile   #3个命令返回相同结果,
northwest       NW      Charles Main        3.0     .98     3       34
northeast       NE       AM Main Jr.        5.1     .94     3       13
north           NO      Margot Weber        4.5     .89     5       9

不使用正则表达式

fgrep 查询速度比grep命令快,但是不够灵活:它只能找固定的文本,而不是规则表达式。

如果你想在一个文件或者输出中找到包含星号字符的行

fgrep  &#39;*&#39; /etc/profile
for i in /etc/profile.d/*.sh ; do

或
grep -F &#39;*&#39; /etc/profile
for i in /etc/profile.d/*.sh ; do


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:리눅스 grep 명령다음 기사:리눅스 grep 명령