Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Use grep in Linux: Search Text, Logs, and Directories

Use practical grep examples for literal text, regular expressions, recursive searches, line numbers, and accurate counting.

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.

Instructions on how to use the Grep command in Linux Picture 1

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.

Instructions on how to use the Grep command in Linux Picture 2

Using grep to search text on Linux.

Flags that change what grep returns

FlagWhat it does
-nPrefixes a match with its line number.
-lPrints filenames that have a match. This is a lowercase L.
-cCounts matching lines per input file.
-oPrints matched portions on separate lines.
-w / -xMatches a whole word or a whole line, respectively.
-vSelects lines that do not match.
-r / -RSearch 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.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.