grep命令详解

本文详细介绍了grep命令的基础用法,包括单个文件搜索、多个文件检索、大小写不敏感搜索、使用正则表达式、搜索整个单词、显示前后行、高亮显示搜索内容、递归搜索、不匹配搜索、统计匹配行数、只显示文件名、只显示匹配字串、显示匹配位置和行号等特性。并通过实例展示了如何在实际场景中应用这些功能。

转自:http://www.cnblogs.com/kuyuecs/archive/2012/07/13/2589988.html


首先创建我们练习grep命令时需要用到的demo文件demo_file。

$ cat demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.

Two lines above this line is empty.
And this is the last line.

1.从单个文件中搜索指定的字串

grep的基础用法是如下例的从指定的文件中搜索特定的字串。

语法:
grep "literal_string" filename

 

$ grep "this" demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

2. 在多个文件中检索指定的字串

语法:
grep "string" FILE_PATTERN


先拷贝demo_file为demo_file1。grep的结果在符合条件的行前将包括文件名。当文件名包含元字符时,linux shell会将匹配的所有文件作为输入到grep中去。

 

$ cp demo_file demo_file1

$ grep "this" demo_*
demo_file:this line is the 1st lower case line in this file.
demo_file:Two lines above this line is empty.
demo_file:And this is the last line.
demo_file1:this line is the 1st lower case line in this file.
demo_file1:Two lines above this line is empty.
demo_file1:And this is the last line.

3. 用 grep -i 进行大小写无关的搜索

语法:
grep -i "string" FILE


也是一个基本用法,对搜索的字串忽略大小写,因此下例中匹配“the”, “THE” and “The”。

 

$ grep -i "the" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
And this is the last line.

4. 使用用正则表达式

语法:
grep "REGEX" filename


如果你能有效地利用正则表达式,这是个很有用的特点。在下面的例子中,搜索全部以“lines”开始以“empty”结束的字串,如搜索“lines[之间任意字]empty” ,并且忽略大小写。

 

$ grep -i "lines.*empty" demo_file
Two lines above this line is empty.

 

正则表达式遵循的几个重复的操作

  • ? 最多匹配一次
  • * 匹配零次或者任意多次
  • + 匹配一次以上
  • {n} 匹配n次
  • {n,} 最少匹配n次
  • {,m} 最多匹配m次
  • {n,m} 匹配n到m次

5. 用grep -w搜索整个词,而不是词中的部分字串

使用-w选项搜索一个单词,并且避免搜索到词中的部分字串。

下例搜索"is"。如果不加-w选项,将显示“is”, “his”, “this” 等所有包含“is”的行。

$ grep -i "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
Two lines above this line is empty.
And this is the last line.


下例使用了-w选项,请注意结果中不包含 “This Line Has All Its First Character Of The Word With Upper Case”, 虽然 “This”中包含“is”。

$ grep -iw "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

6. 使用grep -A, -B and -C显示之前、之后、前后的几行

当使用grep搜索大文件时,显示匹配行附近的多行数据是一个很有用的功能。


创建如下文件

$ cat demo_text
4. Vim Word Navigation

You may want to do several navigation in relation to the words, such as:

* e - go to the end of the current word.
* E - go to the end of the current WORD.
* b - go to the previous (before) word.
* B - go to the previous (before) WORD.
* w - go to the next word.
* W - go to the next WORD.

WORD - WORD consists of a sequence of non-blank characters, separated with white space.
word - word consists of a sequence of letters, digits and underscores.

Example to show the difference between WORD and word

* 192.168.1.1 - single WORD
* 192.168.1.1 - seven words.
6.1 显示匹配行之后的N行

-A

语法:
grep -A "string" FILENAME


下例显示匹配行和之后的3行数据

$ grep -A 3 -i "example" demo_text
Example to show the difference between WORD and word

* 192.168.1.1 - single WORD
* 192.168.1.1 - seven words.
6.2显示匹配行之前的N行

-B

语法:
grep -B "string" FILENAME


下例显示匹配行和之前的2行数据

$ grep -B 2 "single WORD" demo_text
Example to show the difference between WORD and word

* 192.168.1.1 - single WORD
6.3显示匹配行前后的N行

-C 显示之前的n行,之后的n行数据.

$ grep -C 2 "Example" demo_text
word - word consists of a sequence of letters, digits and underscores.

Example to show the difference between WORD and word

* 192.168.1.1 - single WORD

7.通过GREP_OPTIONS高亮显示搜索的字串

如果你希望搜索的字串高亮显示在结果中,可以试用以下的办法。

通过修改GREP_OPTIONS对搜索字串高亮显示。

 

$ export GREP_OPTIONS='--color=auto' GREP_COLOR='100;8'

$ grep this demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

8. 用grep -r递归搜索全部的文件

如果想查找当前目前以及其子目录的全部文件时,可以使用 -r 选项。如下例

$ grep -r "ramesh" *

9. 使用grep -v进行不匹配

可以使用-v选项显示不匹配搜索字串的行。下例显示demo_text文件中不包含“go”的行

$ grep -v "go" demo_text
4. Vim Word Navigation

You may want to do several navigation in relation to the words, such as:

WORD - WORD consists of a sequence of non-blank characters, separated with white space.
word - word consists of a sequence of letters, digits and underscores.

Example to show the difference between WORD and word

* 192.168.1.1 - single WORD
* 192.168.1.1 - seven words.

10. 显示不匹配全部模式的行

语法:
grep -v -e "pattern" -e "pattern"

 

创建如下例子文件

$ cat test-file.txt
a
b
c
d

$ grep -v -e "a" -e "b" -e "c" test-file.txt
d

11.用grep -c 统计匹配的行数

语法:
grep -c "pattern" filename

 

$ grep -c "go" demo_text
6


统计不匹配的行数

$ grep -v -c this demo_file
4

12. 用grep -l 只显示文件名

$ grep -l this demo_*
demo_file
demo_file1

13. 只显示匹配的字串

缺省显示匹配字串的所在行,可以使用-o选项只显示匹配的字串。这项功能当使用正则表达式时比较有用处。

$ grep -o "is.*line" demo_file
is line is the 1st lower case line
is line
is is the last line

14. 显示匹配的位置

语法:
grep -o -b "pattern" file

 

$ cat temp-file.txt
12345
12345

$ grep -o -b "3" temp-file.txt
0:3
6:3


注意: 以上输出显示的不是行内的位置,而是整个文件中的字节byte位置

15. 用 grep -n 在输出时显示行号

行号从1开始

$ grep -n "go" demo_text
5: * e - go to the end of the current word.
6: * E - go to the end of the current WORD.
7: * b - go to the previous (before) word.
8: * B - go to the previous (before) WORD.
9: * w - go to the next word.
10: * W - go to the next WORD.
来源:http://www.cnblogs.com/xuxm2007/archive/2011/01/10/1932288.html

<think>我们被要求详细解释grep命令的用法及选项说明。根据引用[1][2][3][5]的内容,我们可以整理出grep命令的详细用法。注意,引用[4]提供了一个使用sed和grep结合的例子,但我们的重点是grep本身。grep(GlobalRegularExpressionPrint)是一个强大的文本搜索工具,用于在文件中搜索包含特定模式(字符串或正则表达式)的行,并将匹配的行打印出来。###一、基本命令格式```bashgrep[选项]'搜索模式'文件名```###二、常用选项说明以下选项基于引用[3]和[5]进行整理:1.**-i(ignore-case)**忽略大小写进行匹配。示例:`grep-i'hello'file.txt`会匹配"hello"、"Hello"、"HELLO"等。2.**-v(invert-match)**反向匹配,即显示不包含模式的行。示例:`grep-v'error'file.txt`显示所有不含"error"的行。3.**-w(word-regexp)**按单词匹配,只匹配整个单词。示例:`grep-w'is'file.txt`只匹配独立的单词"is",不匹配"this"中的"is"。4.**-o(only-matching)**只打印匹配的部分(每行中匹配的部分单独成行)。示例:`grep-o'pattern'file.txt`5.**-c(count)**统计匹配到的行数(不是匹配的次数)。示例:`grep-c'error'file.txt`返回包含"error"的行数。6.**-n(line-number)**显示匹配行及其行号。示例:`grep-n'error'file.txt`7.**-r或-R(recursive)**递归搜索目录下的所有文件。示例:`grep-r'main'/path/to/dir/`8.**-l(files-with-matches)**只列出包含匹配模式的文件名。示例:`grep-l'main'*.c`9.**-L(files-without-match)**列出不包含匹配模式的文件名。示例:`grep-L'main'*.c`10.**-Anum(after-context)**显示匹配行及后面的num行。示例:`grep-A2'error'file.txt`显示匹配行和其后2行。11.**-Bnum(before-context)**显示匹配行及前面的num行。示例:`grep-B2'error'file.txt`12.**-Cnum(context)**显示匹配行及前后各num行。示例:`grep-C2'error'file.txt`13.**-e(regexp)**指定多个模式,或用于保护以减号(-)开头的模式。示例:`grep-e'pattern1'-e'pattern2'file.txt`14.**-E(extended-regexp)**使用扩展正则表达式(等同于egrep)。示例:`grep-E'pattern1|pattern2'file.txt`15.**-F(fixed-strings)**将模式视为固定字符串(等同于fgrep)。示例:`grep-F'$PATH'file.txt`会匹配'$PATH'这个字符串,而不会将其中的'$'视为正则表达式元字符。16.**-q(quiet)**静默模式,不输出任何内容,只根据匹配结果返回退出状态(0表示匹配成功,1表示未匹配)。示例:`grep-q'pattern'file.txt`然后通过`$?`查看结果。17.**--color**对匹配的字符串进行高亮显示。示例:`grep--color'pattern'file.txt`###三、正则表达式基础grep默认支持基本正则表达式(BRE),使用`-E`选项则支持扩展正则表达式(ERE)。以下是一些常用元字符:-**基本正则表达式(BRE)**:-`.`:匹配任意一个字符。-`*`:匹配前一个字符0次或多次。-`^`:匹配行首。-`$`:匹配行尾。-`[]`:字符集,匹配其中任意一个字符。-`[^]`:否定字符集,匹配不在其中的任意字符。-`\`:转义字符。-**扩展正则表达式(ERE)**(使用`-E`选项):-`+`:匹配前一个字符1次或多次。-`?`:匹配前一个字符0次或1次。-`|`:或,匹配多个模式之一。-`()`:分组。-`{}`:指定重复次数,如`{n}`表示重复n次,`{n,m}`表示重复n到m次。###四、实用技巧示例1.**查找多个模式**(引用[2]):```bashgrep-e'error'-e'warning'file.log#或使用扩展正则表达式grep-E'error|warning'file.log```2.**递归搜索并显示文件名**(引用[2]):```bashgrep-rl'DEBUG'/var/log```3.**统计匹配行数**:```bashgrep-c'GET/api/user'access.log```4.**结合find使用**(引用[4]):```bashfind/etc-typef-execgrep-l'root'{}\;```5.**高亮显示匹配**:可以将`--color=auto`添加到`~/.bashrc`中使grep默认高亮:```bashaliasgrep='grep--color=auto'```6.**忽略二进制文件**:使用`-I`选项(大写i)来忽略二进制文件:```bashgrep-rI'text'/path```###五、注意事项-当搜索包含空格或特殊字符的字符串时,使用单引号将模式括起来。-使用`-r`递归搜索时,可能会搜索到大量文件,建议先限制文件类型(如通过`find`命令筛选)。-使用`-v`选项时,注意它排除的是整行,即使该行只有部分匹配也会被排除。###六、相关命令-**egrep**:等同于`grep-E`(扩展正则表达式)。-**fgrep**:等同于`grep-F`(固定字符串,速度快但不支持正则表达式)。###七、退出状态-0:匹配成功。-1:未匹配。-2:发生错误。###八、性能优化-对于大文件,使用`-mnum`选项限制匹配次数(匹配num行后停止)。-使用`-F`(固定字符串)比正则表达式更快。-使用`--include`和`--exclude`来限定文件类型,例如:```bashgrep-r--include='*.txt''pattern'/path```§§相关问题§§1.grep和egrep、fgrep有什么区别?2.如何用grep同时匹配两个不同的字符串(AND关系)?3.如何排除特定目录进行递归搜索?4.如何使用grep在压缩文件中搜索?</think>### grep 命令详解 `grep`(Global Regular Expression Print)是 Linux/Unix 系统中用于文本搜索的核心工具,支持正则表达式匹配。以下是详细用法及选项说明: --- #### 一、基础语法 ```bash grep [选项] '搜索模式' 文件名 ``` --- #### 二、常用选项说明 | 选项 | 功能描述 | 示例 | |------|----------|------| | **-i** | 忽略大小写 | `grep -i 'root' /etc/passwd` | | **-v** | 反向匹配(显示不含模式的行) | `grep -v 'nologin' /etc/passwd` | | **-w** | 精确匹配单词(非子串) | `grep -w 'bin' /etc/passwd` | | **-o** | 仅显示匹配部分 | `grep -o 'root' /etc/passwd` | | **-c** | 统计匹配行数 | `grep -c 'bash' /etc/passwd` | | **-n** | 显示匹配行号 | `grep -n 'root' /etc/passwd` | | **-r** | 递归搜索目录 | `grep -r 'error' /var/log/` | | **-l** | 仅输出匹配文件名 | `grep -rl 'root' /etc/` | | **-L** | 输出不匹配的文件名 | `grep -L 'root' /etc/*.conf` | | **-A** | 显示匹配行及后 N 行 | `grep -A 3 'kernel' /var/log/syslog` | | **-B** | 显示匹配行及前 N 行 | `grep -B 2 'error' app.log` | | **-C** | 显示匹配行前后各 N 行 | `grep -C 1 'warning' system.log` | | **-E** | 启用扩展正则表达式 | `grep -E 'error|warn' app.log` | | **-F** | 禁用正则(按字面搜索) | `grep -F '$PATH' .bashrc` | | **--color** | 高亮显示匹配结果 | `grep --color 'root' /etc/passwd` | --- #### 三、正则表达式应用 | 模式 | 说明 | 示例 | |-------------|------------------------|--------------------------| | `^` | 匹配行首 | `grep '^root' file` | | `$` | 匹配行尾 | `grep 'bash$' file` | | `.` | 匹配任意单个字符 | `grep 'r..t' file` | | `*` | 匹配前字符 0 次或多次 | `grep 'lo*se' file` | | `[abc]` | 匹配指定字符之一 | `grep '[aeiou]' file` | | `[^abc]` | 匹配非指定字符 | `grep '[^0-9]' file` | | `|` | 逻辑或(需 -E 支持) | `grep -E 'err|warn' log` | | `()` | 分组匹配(需 -E 支持) | `grep -E '(error|fail)'` | --- #### 四、实用场景示例 1. **多关键词搜索** ```bash grep -E 'error|warning|critical' system.log ``` 2. **递归统计匹配文件数** ```bash grep -rl 'root' /etc | wc -l ``` 3. **过滤时间范围日志**(结合 `sed`)[^4] ```bash sed -n '/2023-08-01 09:00/,/2023-08-01 10:00/p' app.log | grep 'timeout' ``` 4. **删除匹配内容的文件** ```bash grep -rl 'DEBUG' /var/log | xargs rm -f ``` 5. **统计代码中函数调用次数** ```bash grep -c 'function_name' *.py ``` --- #### 五、性能优化技巧 1. 使用 `-F` 替代正则可提速 2-3 倍(固定字符串搜索) 2. 大文件搜索时用 `-m NUM` 限制匹配次数 3. 结合 `find` 并行处理: ```bash find /var/log -type f -exec grep -H 'error' {} + ``` --- #### 六、注意事项 1. 特殊字符需转义:`$`、`*`、`[` 等需用 `\` 转义(如 `grep '\$PATH' file`) 2. 二进制文件需加 `-a` 选项:`grep -a 'text' binary_file` 3. 默认使用 **基本正则表达式**(BRE),`-E` 启用扩展正则(ERE) > 更多正则表达式规则参考:`man 7 regex`[^5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值