Table of Contents
Use grep to find lines that match text or a pattern in a file. For example, grep -in 'error' app.log prints matching lines with their line numbers and ignores case.

Search files, directories, or command output
grep -nF 'user.name' config.txt
grep -rin --include='*.log' -- 'timeout' ./logs
grep -nC 2 -- 'ERROR' app.log
journalctl -u example.service --no-pager | grep -i -- 'failed'
The first example uses -F so the period matches a literal period. The second searches nested directories and limits the selected filenames to *.log. The third shows two lines on either side of each match. The last reads another command’s output through a pipe. Replace example.service with a unit you can read.

Using grep to search text on Linux.
Flags that change what grep returns
| Flag | What it does |
|---|---|
-n | Prefixes a match with its line number. |
-l | Prints filenames that have a match. This is a lowercase L. |
-c | Counts matching lines per input file. |
-o | Prints matched portions on separate lines. |
-w / -x | Matches a whole word or a whole line, respectively. |
-v | Selects lines that do not match. |
-r / -R | Search recursively. With GNU grep, -R also follows symlinks discovered during the search. |
To count each occurrence of a nonempty literal pattern, use grep -oF -- 'ERROR' app.log | wc -l. Use grep -cF -- 'ERROR' app.log to count lines that contain one or more occurrences.
Use a regular expression when the pattern varies
grep -nE '^(ERROR|WARN) ' app.log accepts either word at the start of a line. Quote the pattern so the shell passes it as written. Use -- before a pattern that starts with a dash. GNU grep normally exits with 0 when it selects a line, 1 when it selects none, or 2 for an error. See the GNU grep manual and the Linux Fundamentals course for more shell practice.
Reader Comments 0
Sign in with email or Google to join the discussion.