OSDN Git Service

Regular updates
[twpd/master.git] / grep.md
1 ---
2 title: GNU grep
3 category: CLI
4 layout: 2017/sheet
5 updated: 2021-08-23
6 ---
7
8 ### Usage
9 {: .-prime}
10
11 ```bash
12 grep <options> pattern <file...>
13 ```
14
15 ### Matching options
16
17 ```bash
18 -e, --regexp=PATTERN
19 -f, --file=FILE
20 -i, --ignore-case
21 -v, --invert-match
22 -w, --word-regexp
23 -x, --line-regexp
24 ```
25
26 ### Pattern options
27
28 ```bash
29 -F, --fixed-strings   # list of fixed strings
30 -G, --basic-regexp    # basic regular expression (default)
31 -E, --extended-regexp # extended regular expression
32 -P, --perl-regexp     # perl compatible regular expression
33 ```
34
35 ### Expressions
36
37 #### Basic Regular Expressions (BRE)
38
39 In BRE, these characters have a special meaning unless they are escaped with a backslash:
40
41 `^ $ . * [ ] \`
42
43 However, these characters do not have any special meaning unless they are escaped with a backslash:
44
45 `? + { } | ( )`
46         
47 #### Extended Regular Expressions (ERE)
48
49 ERE gives all of these characters a special meaning unless they are escaped with a backslash:
50
51 `^ $ . * + ? [ ] ( ) | { }`
52
53 #### Perl Compatible Regular Expressions (PCRE)
54
55 PCRE has even more options such as additional anchors and character classes, lookahead/lookbehind, conditional expressions, comments, and more. See the [regexp cheatsheet](/regexp).
56
57 ### Output Options
58
59 ```bash
60 -c, --count           # print the count of matching lines. suppresses normal output
61     --color[=WHEN]    # applies color to the matches. WHEN is never, always, or auto
62 -m, --max-count=NUM   # stop reading after max count is reached
63 -o, --only-matching   # only print the matched part of a line
64 -q, --quiet, --silent
65 -s, --no-messages     # suppress error messages about nonexistent or unreadable files
66 ```
67
68 ### Context Options
69
70 ```bash
71 -B NUM, --before-context=NUM  # print NUM lines before a match
72 -A NUM, --after-context=NUM   # print NUM lines after a match
73 -C NUM, -NUM, --context=NUM   # print NUM lines before and after a match
74 ```
75
76 ### Examples
77
78 ```bash
79 # Case insensitive: match any line in foo.txt
80 # that contains "bar"
81 grep -i bar foo.txt
82
83 #  match any line in bar.txt that contains
84 # either "foo" or "oof"
85 grep -E "foo|oof" bar.txt
86
87 # match anything that resembles a URL in
88 # foo.txt and only print out the match
89 grep -oE "https?:\/\/((\w+[_-]?)+\.?)+" foo.txt
90
91 # can also be used with pipes:
92 # match any line that contains "export" in
93 # .bash_profile, pipe to another grep that
94 # matches any of the first set of matches
95 # containing "PATH"
96 grep "export" .bash_profile | grep "PATH"
97
98 # follow the tail of server.log, pipe to grep
99 # and print out any line that contains "error"
100 # and include 5 lines of context
101 tail -f server.log | grep -iC 5 error
102 ```