In Linux, grep
supports regular expressions (regex), which allow for pattern matching more complex than simple substring searches. Here’s how you can use grep
with regular expressions:
- Basic regex search:
Search for lines containing a pattern defined by a regular expression:
grep 'regular_expression' filename
- Case-insensitive search:
Perform a case-insensitive regex search:
grep -i 'regular_expression' filename
- Extended regex syntax:
Use the-E
option to enable extended regular expressions (this is the default on many systems):
grep -E 'regular_expression' filename
- Search for lines starting with a pattern:
Only match lines that begin with the specified pattern:
grep '^regular_expression' filename
- Search for lines ending with a pattern:
Only match lines that end with the specified pattern:
grep 'regular_expression$' filename
- Use character classes:
Search for lines that contain any vowel (both cases):
grep '[aeiouAEIOU]' filename
- Multiple patterns:
Search for lines that contain any of the given patterns:
grep -E '(pattern1|pattern2|pattern3)' filename
- Quantifiers:
Search for lines with exactly three digits:
grep -E '(\\d){3}' filename
- Character ranges:
Search for lines that contain a lowercase letter between ‘a’ and ‘m’:
grep '[a-m]' filename
- Greedy and lazy quantifiers:
Search for the longest string that starts with ‘foo’ and ends before a ‘bar’:
grep -E 'foo.*bar' filename grep -E 'foo.*?bar' filename
- Grouping and backreferences:
Search for lines that contain the same two-digit number twice:
grep -E '(\\d\\d).*\\1' filename
- Negation:
Search for lines that do not contain a digit:
grep -v '[0-9]' filename
- Bracket expressions:
Search for lines that contain any character except the specified ones:
grep -E '[^aeiou]' filename
- Recursive search with regex:
Search recursively for a pattern in all files within a directory:
grep -r 'regular_expression' /path/to/directory
- Using Perl-compatible regular expressions (PCRE):
Use the-P
option for Perl-compatible regular expressions:bash grep -P 'regular_expression' filename
Remember to enclose your regular expressions in single quotes '
to prevent the shell from interpreting any special characters. Adjust the regular expressions according to your specific search requirements.