linux-command
Version:
257 lines (194 loc) • 8.37 kB
Markdown
grep
===
强大的文本搜索工具
global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。用于过滤/搜索的特定字符。可使用正则表达式能配合多种命令使用,使用上十分灵活。
### 选项
```shell
-a --text # 不要忽略二进制数据。
-A <显示行数> --after-context=<显示行数>
-b --byte-offset
-B<显示行数> --before-context=<显示行数>
-c --count
-C<显示行数> --context=<显示行数>或-<显示行数>
-d<进行动作> --directories=<动作>
-e<范本样式> --regexp=<范本样式>
-E --extended-regexp
-f<范本文件> --file=<规则文件>
-F --fixed-regexp
-G --basic-regexp
-h --no-filename
-H --with-filename
-i --ignore-case
-l --file-with-matches
-L --files-without-match
-n --line-number
-P --perl-regexp
-q --quiet或--silent
-R/-r --recursive
-s --no-messages
-v --revert-match
-V --version
-w --word-regexp
-x --line-regexp
-y
-o
-m <num> --max-count=<num>
```
```shell
^
$
.
*
.*
[]
[^]
\(..\)
\<
\>
x\{m\}
x\{m,\}
x\{m,n\}
\w
\W
\b
```
在文件中搜索一个单词,命令会返回一个包含 **“match_pattern”** 的文本行:
```shell
grep match_pattern file_name
grep "match_pattern" file_name
```
在多个文件中查找:
```shell
grep "match_pattern" file_1 file_2 file_3 ...
```
输出除之外的所有行 **-v** 选项:
```shell
grep -v "match_pattern" file_name
```
标记匹配颜色 **--color=auto** 选项:
```shell
grep "match_pattern" file_name --color=auto
```
使用正则表达式 **-E** 选项:
```shell
grep -E "[1-9]+"
egrep "[1-9]+"
```
使用正则表达式 **-P** 选项:
```shell
grep -P "(\d{3}\-){2}\d{4}" file_name
```
只输出文件中匹配到的部分 **-o** 选项:
```shell
echo this is a test line. | grep -o -E "[a-z]+\."
line.
echo this is a test line. | egrep -o "[a-z]+\."
line.
```
统计文件或者文本中包含匹配字符串的行数 **-c** 选项:
```shell
grep -c "text" file_name
```
搜索命令行历史记录中 输入过 `git` 命令的记录:
```shell
history | grep git
```
输出包含匹配字符串的行数 **-n** 选项:
```shell
grep "text" -n file_name
cat file_name | grep "text" -n
grep "text" -n file_1 file_2
```
打印样式匹配所位于的字符或字节偏移:
```shell
echo gun is not unix | grep -b -o "not"
7:not
```
搜索多个文件并查找匹配文本在哪些文件中:
```shell
grep -l "text" file1 file2 file3...
```
在多级目录中对文本进行递归搜索:
```shell
grep "text" . -r -n
```
忽略匹配样式中的字符大小写:
```shell
echo "hello world" | grep -i "HELLO"
```
选项 **-e** 制动多个匹配样式:
```shell
echo this is a text line | grep -e "is" -e "line" -o
is
is
line
cat patfile
aaa
bbb
echo aaa bbb ccc ddd eee | grep -f patfile -o
```
在grep搜索结果中包括或者排除指定文件:
```shell
grep "main()" . -r --include *.{php,html}
grep "main()" . -r --exclude "README"
grep "main()" . -r --exclude-from filelist
```
使用0值字节后缀的grep与xargs:
```shell
echo "aaa" > file1
echo "bbb" > file2
echo "aaa" > file3
grep "aaa" file* -lZ | xargs -0 rm
```
grep静默输出:
```shell
grep -q "test" filename
```
打印出匹配文本之前或者之后的行:
```shell
seq 10 | grep "5" -A 3
5
6
7
8
seq 10 | grep "5" -B 3
2
3
4
5
seq 10 | grep "5" -C 3
2
3
4
5
6
7
8
echo -e "a\nb\nc\na\nb\nc" | grep a -A 1
a
b
--
a
b
```
**grep** (