Working with grep
grep
stands for Global Regular Expression Print. It searches for patterns (text strings or regex) in files or input streams and prints matching lines.
Basic Syntax
grep [options] pattern [file...]
Common Usage Examples
Search in a file
grep "error" /var/log/syslog
Finds lines containing "error"
in the file.
Search recursively in directories
grep -r "TODO" /home/user/projects/
Searches for "TODO"
in all files under the given directory.
Case-insensitive search
grep -i "warning" logfile.txt
Matches warning
, Warning
, or WARNING
.
Count matching lines
grep -c "fail" result.log
Returns how many lines contain "fail"
.
Display line numbers
grep -n "404" access.log
Adds line numbers before matching lines.
Use regular expressions
grep "^start" file.txt
Matches lines starting with “start”.
grep "end$" file.txt
Matches lines ending with “end”.
Invert match (show non-matching lines)
grep -v "success" log.txt
Displays lines that do not contain "success"
.
Search in output of a command (stream)
dmesg | grep usb
Searches for “usb” in the kernel ring buffer output.
Highlight matches
Most modern systems highlight matches by default, but you can force it:
grep --color=always "pattern" file.txt
Important Options Summary
Option | Description |
---|---|
-i | Case-insensitive |
-v | Invert match |
-r or -R | Recursive search in directories |
-n | Show line numbers |
-c | Count matching lines |
-l | Show only filenames with matches |
-w | Match whole words only |
-e | Use multiple patterns |
--color | Highlight matching text |
Piping with grep
You can use grep
with pipes to search command output:
ps aux | grep apache
Finds Apache-related processes.
journalctl -xe | grep sshd
Filters SSH-related logs.
Summary
grep
is essential for searching text patterns in files or output.- Works with exact strings or regex.
- Combine with pipes for powerful log and process filtering.
- Use options to customize search behavior (case sensitivity, line numbers, etc.).