Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Search Text with the grep Command in Linux

grep finds lines that match a word or pattern in files or in the output of other commands.

VPS and Cloud Servers2 min read1 screenshot

Why grep is useful

  • It works on code, logs, text files and even binary data.
  • It scans large files very fast.
  • It supports regular expressions for exact patterns.
  • It is the first tool most admins use to read logs.

Basic use

grep pattern files

Search for the word "error" in a log:

grep error system.log

See all options:

grep --help
The help page of grep

Common options

OptionWhat it does
-iIgnore case
-vShow lines that do not match
-cCount the matching lines
-nShow line numbers
-rSearch all files in a folder and below
-lList only the names of the files that match
-wMatch whole words only
-A 2, -B 2, -C 2Show lines after, before or around each match
-EUse extended regular expressions

Examples

Ignore case

grep -i "warning" /var/log/syslog

Lines that do not match

grep -v "debug" app.log

Count matches in files

grep -c warning /var/log/*

Show line numbers

grep -n "failed" /var/log/auth.log

Search a whole folder

grep -r "database_password" /var/www/

Context around a match

grep -A 2 -B 2 "critical error" app.log

This prints two lines before and two lines after each match.

Use grep with other commands

Filter the output of a command

ps aux | grep firefox

Use the output of a command as the pattern

cat /etc/passwd | grep "$(whoami)"

Combine with other tools

grep "error" log.txt | sed 's/error/fixed/g'

Quick recap

  • grep pattern file prints the matching lines.
  • Add -i, -v, -n, -c and -r as needed.
  • Pipe other commands into grep to filter the output.