Log inSign up

Searching files and command output with grep

Run grep "text" file to print every line of the file that contains the text. Add -i to ignore case, -n for line numbers and -r to search a whole directory, as in grep -rn "DB_HOST" /var/www/example.net. For patterns with alternatives or repeats use grep -E, which replaces the old egrep command.

Topic: Linux command line · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What does grep do, and is it installed?

grep reads text line by line and prints the lines that match a pattern. It works on files you name and on the output of other commands through a pipe, which makes it the tool you reach for when a log is too big to read or you need to know which config file sets a value. GNU grep is part of every Ubuntu, Debian, Rocky Linux and AlmaLinux image.

grep --version | head -n 1
grep deploy /etc/passwd
ps aux | grep nginx

The second line prints the account entry for the user deploy. The third filters the process list; it also shows the grep process itself, which you can avoid with pgrep -a nginx. Ubuntu 24.04 has grep 3.11, Debian 12 has 3.8 and Rocky or Alma 9 have 3.6, and every option in this guide works on all of them.

Which options do I use most often?

A handful of flags covers most daily work:

  • -i: ignore upper and lower case.
  • -n: show the line number of each match.
  • -v: invert, print lines that do not match.
  • -w: match whole words only, so port does not match import.
  • -c: print only the count of matching lines.
  • -x: the whole line must match.
  • -m 5: stop after five matches.
  • -q: print nothing, just set the exit status (useful in scripts).
grep -in "listen" /etc/nginx/sites-available/default
grep -c "GET" /var/log/nginx/access.log
grep -vw "root" /etc/group | head

Flags can be combined into one group, as in -inw. Several fixed patterns are given with repeated -e, for example grep -e error -e warn app.log.

How do I search through a whole directory?

Use -r to walk a directory tree, together with -n and often -l, which lists only the names of files that contain a match.

grep -rn "server_name" /etc/nginx/
grep -rl "example.net" /var/www/
grep -rn --include='*.php' "mysqli_connect" /var/www/
grep -rn --exclude-dir=node_modules --exclude-dir=.git "API_URL" ~/app

--include limits the search to file names matching a pattern, and --exclude-dir skips folders that are large and irrelevant. -r does not follow symbolic links found inside the tree; -R does. Reading system folders may need sudo. Combine grep with find when the file selection depends on age or size rather than name.

How do regular expressions work in grep?

By default grep uses basic regular expressions; with -E it switches to extended ones, where |, +, ? and parentheses work without backslashes. The essentials:

  • ^ start of line, $ end of line.
  • . any single character; [.] a literal dot.
  • [0-9] a digit, [[:space:]] whitespace, [^#] anything except a hash.
  • * zero or more, + one or more, {2,4} two to four repeats.
  • a|b either alternative.
grep -E "error|crit|alert" /var/log/nginx/error.log
grep -Ev '^[[:space:]]*(#|$)' /etc/ssh/sshd_config
grep -E '^[0-9]{1,3}([.][0-9]{1,3}){3} ' access.log | head
grep -F "1.2.3.4" access.log

The second line is a favourite: it prints a config file without comments and blank lines, so you see only the active settings. -F treats the pattern as plain text, which avoids surprises when it contains dots or brackets. Use single quotes around patterns so the shell leaves characters such as $ and * alone. egrep and fgrep still exist, but GNU grep marks them as obsolescent since version 3.8, so write grep -E and grep -F in new scripts.

How can I see the lines around a match?

Use -A (after), -B (before) or -C (both sides) with a number of lines. Groups of results are separated by a -- line.

grep -n -A 3 "Traceback" /var/log/app/app.log
grep -B 2 -A 8 "location /api" /etc/nginx/sites-available/example.net
grep -C 5 "Out of memory" /var/log/kern.log

Context is what turns a single error line into something you can act on, such as the stack trace below an exception or the block a config option belongs to. -o does the opposite: it prints only the matched part of each line, which is handy for extracting values like IP addresses or status codes.

How do I use grep to analyse logs?

Pipe the matches into sort, uniq -c and head to turn raw lines into a ranking. Two examples a server admin needs regularly:

sudo grep "Failed password" /var/log/auth.log | grep -oE 'from [0-9.]+' | sort | uniq -c | sort -rn | head
grep -oE '^[0-9.]+' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head
grep -c " 404 " /var/log/nginx/access.log
zgrep -h " 500 " /var/log/nginx/access.log.*.gz | wc -l

The first counts failed SSH logins per source address; on Rocky and Alma read /var/log/secure, and on Debian, where there is no auth.log by default, run journalctl -u ssh | grep "Failed password". The second ranks the busiest client addresses. If the same addresses keep trying passwords, fail2ban can block them automatically, and the SSH hardening tutorial removes password logins altogether. For counting by field rather than by pattern, awk is often shorter, as the sed and awk guide shows.

How do I use grep in scripts?

Rely on the exit status: 0 means at least one line matched, 1 means no match, 2 means an error such as a missing file. With -q grep prints nothing and stops at the first match.

if grep -q "^deploy:" /etc/passwd; then
  echo "user exists"
fi
grep -qxF "127.0.1.1 web1" /etc/hosts || echo "127.0.1.1 web1" | sudo tee -a /etc/hosts

The second line adds a hosts entry only when the exact line is missing, so running the script twice does not duplicate it. The bash conditionals guide covers more of these tests.

Why does grep find nothing, or too much?

  • No output on a file you know contains the text: check case (-i), and whether the file uses Windows line ends; cat -A shows them.
  • Binary file matches: grep detected binary data. Add -a to treat it as text, or --binary-files=without-match to skip such files.
  • Pattern with dots matches too much: a dot means any character. Use -F or [.].
  • Shell expanded your pattern: quote it, especially when it contains * or ?.
  • Very slow recursive search: exclude large folders with --exclude-dir, or narrow the start directory.

Questions about Search text with grep

What is the difference between grep, egrep and fgrep?

egrep is grep -E (extended regex) and fgrep is grep -F (fixed strings). The short names are obsolescent, so use the flags.

How do I search for a word that starts with a dash?

End the options with -- or use -e: grep -- "-v" file or grep -e "-v" file.

Does grep support Perl style patterns?

GNU grep has -P for Perl compatible expressions, such as lookarounds and \d. It is available on all four distributions covered here.

How do I highlight matches?

Interactive shells usually alias grep to grep --color=auto. Use --color=always when piping into less -R.

Can grep search compressed logs?

Yes, with zgrep, which accepts the same options and reads .gz files directly.

How do I list files that do not contain a pattern?

Use grep -L pattern files, the opposite of -l.