1. grep basic syntax
The role of grep is to search. Unlike find, grep is as follows:
Find is used to search for directories and file names.
Grep is basically used to retrieve file content, strings, etc.
grep [OPTIONS] PATTERN [FILE...] grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
Options: (the most common)
-A search by text file
-C: calculates the number of matching rows.
-I case-insensitive
-N by the way, the output row number
-V reverse selection, that is, finding rows without a search string
Pattern:
(1) string to be searched
(2) Basic Regular Expression
(3) extended regular expression (The-e parameter needs to be added)
2. Select [] for the basic regular expression 2.1
[ABC] matches any character in the string ABC.
Available scope-
[A-Z]: match all lowercase English characters
[A-Z]: match all uppercase English characters
[0-9]: Match All numbers
[A-Za-Z]: match all English characters
2.2 .*
* In Bash has different meanings from regular expressions.
Regular Expression:
.: Represents any character
*: Indicates that there are 0 or more characters. For example, GX * can match one or more X characters After G: G, GX, gxx, gxxxx, etc,
End of the first line ^ $
^ Ex: Match ex to the beginning of a row
Tion $: Match tion at the end of a row
2.4 times {}
{N} |
NIs a non-negative integer. MatchedNTimes. |
{N,} |
NIs a non-negative integer. At least matchNTimes. |
{N,M} |
MAndNAll are non-negative integers, whereN<=M. Least matchNTimes and most matchingMTimes. |
Note that {} has special meaning in shell, so use \ escape as a regular expression.
3. Extended regular expressions are mainly used to add or | and () functions for basic regular expressions.
3.1 or |
Pattern1 | pattern2
Implement matching pattern1 or pattern2
We can also see that '|' has a higher priority than other characters (except parentheses of course)
Example: string matching string or char
grep -E 'string|char'
Matches string or char strings starting
grep -E '^string|^char'
3.2 () parentheses
It is the same as the parentheses you learned in elementary school.
Matches string or char strings starting
grep -E '^(string|char)'
4. Regular Expression
For more information about regular expressions, see:
Regular Expression
Grep and Regular Expression