Grep 速查表

介绍

rep - print lines that match patterns

语法

grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command.

A FILE of “-” stands for standard input. If no FILE is given,recursive searches examine the working directory and nonrecursive searches read standard input.

1
2
3
4
grep [options...] [pattern] [file...]
# option参数和file参数, 可以是0个或者多个, pattern 可以是一或多个
# pattern 支持正则表达式
# file 支持 通配符
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

# -i 忽略大小写
grep -i ^DA demo.txt

# Search only for the full word, -w
# 仅匹配整个单词, 如下面的例子, "off" 不会被匹配到
grep -w "of" demo.txt

# Display 3 lines after matching string, -A
grep -A 3 'Exception' error.log

# Display 4 lines before matching string, -B
grep -B 4 'Exception' error.log

# Display 5 lines around matching string, -C
grep -C 5 'Exception' error.log

# Recursive search (within subdirs), -r
# -r 递归
grep -r 'quickref.me' /var/log/nginx/

# -v 反向查找, 只打印不匹配的行
grep -v 'warning' /var/log/syslog

# Use regex (lines starting with 'al'), -e
# 正则表达式
grep -e '^al' filename

# Extended regex (lines containing jason or jackson), -E
grep -E 'ja(s|cks)on' filename

# -c 打印匹配的行数
grep -c 'error' /var/log/syslog

# -l 打印匹配的文件名
grep -l 'robot' /var/log/*

# Only show the matching part of the string, -o
grep -o search_string filename

# -n 显示匹配的行号
grep -n "go" demo.txt

# print the file containing the query including thos within subdirs
grep -r ^David ~/some_dir/*

# print the name of the file(s) which matches the query
# --file-with-matches
grep -l ^David ~/some_dir/*

# -L --files-without-match
# 
grep -rL 'date = ' ./content/*/*.md

Grep Command Cheat Sheet & Quick Reference

shell脚本——grep详解 - 知乎