GREP
On this page
Introduction
Full name Global Regular Expression Print, originated from a Unix editor ed
command g/re/p
,
where g
(global) is global matching, re
(regular expression) is regular expression, p
(print) is print.
Therefore, the grep
tool is essentially used to globally match regular expressions and print the results.
Additionally, egrep
, fgrep
, and rgrep
are respectively equivalent to grep -E
, grep -F
, and grep -r
.
These variants have been deprecated, but are still provided for backward compatibility.
Moreover, if regular expressions are not used, using the -F
option will be faster,
because by default, even if no regular expression is used, grep
will still treat the pattern as a regular expression.
Regular Expressions
grep
defaults to using POSIX regular expressions, divided into the following types based on different options:
Basic Regular Expressions (BRE): Default mode, POSIX standard, some metacharacters (such as
?
,+
,{}
) require escaping with a backslash\
.Extended Regular Expressions (ERE): Used with
grep -E
oregrep
, metacharacters like?
,+
,{}
can be used directly without escaping.Perl-Style Regular Expressions (PCRE): Some
grep
implementations (such as GNUgrep
) provide the-P
option to enable Perl-style regular expressions.
Note
Some grep implementations (such as GNU grep) provide the -P option to enable Perl-style regular expressions.
Common Examples
Reverse Matching
Ignore Case
Count Matching Lines
Fixed String Matching
Recursive Dir Search
Matching File Names
Non-Matching File Names
With Next N Lines
After
With Previous N Lines
Before
With Context N Lines
Context