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/syslogFinds 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.txtMatches warning, Warning, or WARNING.
Count matching lines
grep -c "fail" result.logReturns how many lines contain "fail".
Display line numbers
grep -n "404" access.logAdds line numbers before matching lines.
Use regular expressions
grep "^start" file.txtMatches lines starting with “start”.
grep "end$" file.txtMatches lines ending with “end”.
Invert match (show non-matching lines)
grep -v "success" log.txtDisplays lines that do not contain "success".
Search in output of a command (stream)
dmesg | grep usbSearches 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.txtImportant 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 apacheFinds Apache-related processes.
journalctl -xe | grep sshdFilters SSH-related logs.
Summary
grepis 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.).