The grep
command in Linux is indispensable for filtering and searching through text. Here are some practical examples of how to use grep
in different scenarios:
- Search for a string in a file:
Find lines containing the word “hello” inexample.txt
.
grep 'hello' example.txt
- Case-insensitive search:
Search for “HELLO” without considering case sensitivity.
grep -i 'HELLO' example.txt
- Recursive search in a directory:
Search for “data” in all files within theDocuments
directory, including subdirectories.
grep -r 'data' ~/Documents
- Exclude certain files or directories:
Search for “error” recursively in thelogs
directory, excluding*.log.old
files.
grep -r --exclude='*.log.old' 'error' logs/
- Show line numbers:
Display line numbers for each match of the pattern “error”.
grep -n 'error' logfile.txt
- Print file names:
Only print the names of files containing the word “error”.
grep -l 'error' *.txt
- Count occurrences:
Count how many times the word “error” appears inlogfile.txt
.
grep -c 'error' logfile.txt
- Invert match:
Show all lines that do not contain the word “error”.
grep -v 'error' logfile.txt
- Use regular expressions:
Find lines that start with a digit.
grep '^[0-9]' data.txt
- Context control:
Show the line with the match, as well as two lines before and after.
grep -C 2 'important' document.txt
- Search for multiple patterns:
Find lines that contain either “start” or “end”.
grep -E 'start|end' file.txt
- Exclude a pattern while searching:
Find lines with “start” but not “error”.
grep 'start' file.txt | grep -v 'error'
- Search in compressed files:
Look for the pattern “data” in a compressed log file.
grep 'data' log.gz
- Use with other commands:
Combinegrep
withls
to list only.txt
files containing “report”.
ls -l | grep 'report'
- Search for a pattern and print the byte offset:
Show the pattern “match” and its position in bytes.
grep -bo 'match' file.txt
- Search for a pattern and print the column number:
Find the word “found” and print its column number in the line.
grep -o -E '[a-z]+' file.txt | grep -ob 'found' | cut -d':' -f1
- Pipes and grep:
Usegrep
to filter the output of another command, such as showing processes with “httpd”.
ps aux | grep httpd
- Search for a pattern in a file and exclude a directory:
Search for “pattern” in all.txt
files, excluding thetmp
directory.
grep -r --exclude-dir='tmp' 'pattern' *.txt
- Search using Perl-compatible regular expressions:
Use PCRE to find lines with an IP address pattern.
grep -P '\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b' file.txt
- Interactive search in a file:
Usegrep
with the-i
option in combination withless
for an interactive search.
grep -i 'search_term' largefile.txt | less -i
These examples showcase the flexibility and power of grep
for text searching and data extraction in Linux environments.