Skip to main content

Processing Text with grep

1. Searching with Basic Patterns

Pattern Description Example Result
abc Literal string search grep "abc" file.txt Matches lines containing "abc"
^abc Start of line grep "^abc" file.txt Matches lines starting with "abc"
abc$ End of line grep "abc$" file.txt Matches lines ending with "abc"
. Any single character (except newline) grep "a.c" file.txt Matches "abc", "axc", etc.
^.*$ Any line (equivalent to no pattern) grep "^.*$" file.txt Matches all lines in the file
grep "error" /var/log/syslog

Example: Start of Line Match

grep "^ERROR" /var/log/syslog
Option Values Description
-i grep -i Perform case-insensitive matching
--ignore-case grep --ignore-case Alternative long form of case-insensitive matching
grep -i "hello" file.txt
Note: The -i flag makes grep match patterns regardless of case, useful for searching logs or documentation where capitalization may vary.

Use grep -r to search for patterns recursively in files within directories.

Option Description Example
-r Recursively search subdirectories grep -r "pattern" /path/to/dir
-R Alias for -r grep -R "pattern" /path/to/dir
--include Include only files matching a pattern grep -r --include="*.txt" "pattern" /path/to/dir
--exclude Exclude files matching a pattern grep -r --exclude="*.log" "pattern" /path/to/dir

Example: Recursive search in a directory

grep -r "error" /var/log/

Example: Recursive search with file type filter

grep -r --include="*.py" "def " /home/user/project/

4. Showing Line Numbers

Option Values Description
-n grep -n "pattern" file.txt Show line numbers with matches
--line-number grep --line-number "pattern" file.txt Alternative long form for showing line numbers

Example: Display line numbers for matches

grep -n "error" log.txt
1:ERROR: Failed to connect
5:ERROR: Invalid input

5. Counting Matches

Option Values Description
-c grep -c pattern file Count the number of lines matching the pattern
-c -v grep -c -v pattern file Count lines that do NOT match the pattern
-c -l grep -c -l pattern file Count how many files contain matches (with filenames)

Example: Counting Matches in a File

grep -c "error" /var/log/syslog

Example: Counting Non-Matching Lines

grep -c -v "debug" /var/log/app.log
Note: When using -c, grep outputs only a count number, not the actual matching lines.

6. Inverting Match

Option Values Description
-v grep -v pattern file Invert the match to show lines that do NOT contain the pattern
--invert-match grep --invert-match pattern file Alternative long form of the invert match option

Example: Inverting Match with grep

# Sample file content
echo -e "apple\nbanana\ncherry" > fruits.txt

# Show lines that do NOT contain "banana"
grep -v "banana" fruits.txt
# Output:
# apple
# cherry
Note: The -v flag is useful for filtering out unwanted lines from a dataset.

7. Matching Whole Words

Option Values Description
-w grep -w "word" Match the whole word only

Example: Matching whole words

grep -w "cat" file.txt
# Matches "cat" as a whole word, not "catch" or "concatenate"
Note: The -w option ensures that the pattern matches only at word boundaries, preventing partial matches within larger words.

8. Searching with Context

Option Values Description
-A NUM 5 Print NUM lines after match
-B NUM 3 Print NUM lines before match
-C NUM 2 Print NUM lines before and after match

Example: Show 2 lines before and after each match

grep -C 2 "error" /var/log/syslog

Example: Show 3 lines after each match

grep -A 3 "failed" /var/log/auth.log

9. Using Extended Regex

Feature Description Example
-E Enable extended regular expressions grep -E 'cat|dog' file.txt
+ One or more occurrences of the preceding element grep -E 'a+' file.txt
? Zero or one occurrence of the preceding element grep -E 'colou?r' file.txt
() Grouping expressions for reuse or precedence grep -E '(ab)+' file.txt
| Alternation (OR operator) grep -E 'start|end' file.txt
. Any character except newline grep -E 'a.c' file.txt
^ Start of line anchor grep -E '^hello' file.txt
$ End of line anchor grep -E 'world$' file.txt

Example: Matching IP Addresses

grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}' file.txt

Example: Using Groups for Capture

grep -E '([a-z]+)@\1' file.txt

10. Using Perl-Compatible Regex

Option Values Description
-P perl-compatible-regex Enable Perl-compatible regular expressions (PCRE)
-pcre perl-compatible-regex Alias for -P

Example: Using PCRE to match word boundaries

grep -P '\b\w+ing\b' file.txt

Example: Using PCRE to match multiline patterns

grep -P 'start.*?end' file.txt
Note: PCRE support requires grep to be compiled with PCRE support. Not all systems have this enabled by default.
Warning: PCRE regex syntax is more complex than POSIX basic/extended regex and may not be portable across different systems.

11. Listing Only Filenames

Option Values Description
-l grep -l List only filenames that contain matches

Example: Using -l to list filenames

grep -l "error" /var/log/*.log
Note: The -l option suppresses the actual matching lines and outputs only the names of files containing the pattern.

12. Matching Multiple Patterns

Pattern Description Example Notes
grep 'pattern1\|pattern2' Matches lines containing either pattern1 or pattern2 grep "error\|warning" logfile.txt Uses | as OR operator in extended regex mode
grep -E 'pattern1|pattern2' Extended regex for multiple patterns grep -E "cat|dog" animals.txt Requires -E flag for extended regex
grep -f patterns.txt file.txt Reads multiple patterns from a file grep -f keywords.txt document.txt Each pattern on a separate line in the file
grep -E 'pattern1.*pattern2' Matches lines with pattern1 followed by pattern2 grep -E "start.*end" log.txt Matches any characters between patterns
Note: When using | in basic regex, it must be escaped as \| to avoid interpreting it as a special character.

Was this article helpful?