应用实例
- grep ‘pattern’ filename 搜索filename文章内容
- grep ‘pattern’ filename1 filename2 搜索两篇文件内容
- grep ‘pattern’ * 搜索当前目录内容(语法的意思搜索所有文件)
- grep -r ‘pattern’ * 递归搜索,包含子文件
- grep -l -r ‘pattern’ * 结果只返回匹配的文件名
语法
grep [OPTIONS] PATTERN [FILE…]
grep [OPTIONS] [-e PATTERN]… [-f FILE]… [FILE…]
参数
匹配选择
参数 | 描述 |
---|
-E, –extended-regexp | 拓展的正则表达式 |
-F, –fixed-strings | Interpret PATTERN as a list of fixed strings (instead of regular expressions), separated by newlines, any of which is to be matched. |
-G, –basic-regexp | 基础的正则表达式 |
-P, –perl-regexp | Interpret the pattern as a Perl-compatible regular expression (PCRE). |
匹配控制
参数 | 描述 |
---|
-e PATTERN, –regexp=PATTERN | Use PATTERN as the pattern. |
-f FILE, –file=FILE | Obtain patterns from FILE, one per line. |
-i, –ignore-case | 忽略大小写 |
-v, –invert-match | 反选 |
-w, –word-regexp | 只匹配完整的单词才返回 |
-x, –line-regexp | 只匹配完整的行才返回 |
-y | Obsolete synonym for -i. |
一般的输出控制
参数 | 描述 |
---|
-c, –count | 压缩标准输出; 打印匹配数 |
-L, –files-without-match | 压缩标准的输出; 输出不匹配的文件名 |
-l, –files-with-matches | 压缩标准输出; 只显示文件名 |
-m NUM, –max-count=NUM | Stop reading a file after NUM matching lines. |
-o, –only-matching | Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. |
-q, –quiet, –silent | do not write anything to standard output. |
-s, –no-messages | Suppress error messages about nonexistent or unreadable files. |
输出行前缀控制
参数 | 描述 |
---|
-b, –byte-offset | Print the 0-based byte offset within the input file before each line of output. |
-H, –with-filename | Print the file name for each match. |
-h, –no-filename | Suppress the prefixing of file names on output. |
-n, –line-number | 打印行标 |
-T, –initial-tab | Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. |
-u, –unix-byte-offsets | Report Unix-style byte offsets. |
-Z, –null | Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. |
内容行控制
参数 | 描述 |
---|
-A NUM, –after-context=NUM | Print NUM lines of trailing context after matching lines. |
-B NUM, –before-context=NUM | Print NUM lines of leading context before matching lines. |
-C NUM, -NUM, –context=NUM | Print NUM lines of output context. |
文件路径选择
参数 | 描述 |
---|
-a, –text | Process a binary file as if it were text |
-D ACTION, –devices=ACTION | If an input file is a device, FIFO or socket, use ACTION to process it. |
-d ACTION, –directories=ACTION | If an input file is a directory, use ACTION to process it. |
-I | Process a binary file as if it did not contain matching data; |
-r, –recursive | 递归搜索子文件夹 |
-R, –dereference-recursive | Read all files under each directory, recursively. |
## 其他选择
参数 | 描述 |
---|
-U, –binary | Treat the file(s) as binary. |
-z, –null-data | Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. |
参考文献:
http://www.cnblogs.com/ggjucheng/archive/2013/01/13/2856896.html