Skip to Content
This project is a work in progress. If you have any questions or suggestions, feel free to contact me.
LinuxText ProcessingGrep - Search Text

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

OptionDescription
-iCase-insensitive
-vInvert match
-r or -RRecursive search in directories
-nShow line numbers
-cCount matching lines
-lShow only filenames with matches
-wMatch whole words only
-eUse multiple patterns
--colorHighlight 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.).
Last updated on