Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

grep: search in text

By updated

Improve this page

A service went down last night and its log has thousands of lines: you want the error, its exact line, and what happened just before. grep reads a file or the output of another command, line by line, and prints only the lines that contain a pattern. The trap is that a search with the wrong case or the wrong pattern produces no error message, only an empty or an over-wide result.

The lesson Find files shows the basic grep options next to find. Here, grep is covered on its own, on small files whose content you know. The lesson Regular expressions basics goes deeper into writing patterns; this page only takes what grep needs.

What you will learn

  • Find a line in a file and read the exit code of grep
  • Fix a search that returns nothing, or too many lines
  • Show line numbers, count, and see the lines around a match
  • Write a pattern with the ^ and $ anchors, brackets and extended regex (-E)
  • Search a whole folder and the output of another command
  • Use grep in a script to decide what to do

Prerequisites

You know how to open a Linux terminal, create a folder and move into it with cd. Two notions are used further on: redirections and pipes (|, 2>&1), and, for the end of the page, conditions (if, -eq).

Create the practice folder

All the examples run in ~/grep-lab. The commands below create three text files (app.log, which the map also uses, service.log and config.conf) and two small code folders, src and node_modules. The file contents use French words, which the commands keep: demarrage is "start-up", disque plein "disk full", nouvel essai "new attempt", connexion de "connection from", requete traitee "request processed", date de sauvegarde "backup date", delai depasse apres "timeout after", arret "stop", ligne "line", puis "then", tester "to test" and documenter "to document". The same goes for the later examples: Alerte is "alert", RAS "nothing to report", Lecture impossible "cannot read", fichier "file", texte "text", octet-nul "null byte" and motif "pattern".

Terminal window
mkdir ~/grep-lab && cd ~/grep-lab && {
mkdir src node_modules
cat > app.log <<'FIN'
INFO demarrage
ERROR disque plein
info error=0
DEBUG ping
ERROR puis ERROR
WARN error rate
FIN
cat > service.log <<'FIN'
2025-03-14 08:00:01 INFO demarrage du service
2025-03-14 08:00:02 INFORMATION version 2.4
2025-03-14 08:01:10 ERROR disque plein
2025-03-14 08:01:11 WARN nouvel essai [retry]
2025-03-14 08:01:12 ERROR disque plein
trace : worker.py, ligne 42
2025-03-14 08:02:00 INFO connexion de 192.168.1.10
2025-03-14 08:02:05 INFO requete 12345 traitee
2025-03-14 08:03:00 DEBUG date de sauvegarde 2025-03-13
2025-03-14 08:04:00 ERROR delai depasse apres 30 s
2025-03-14 08:04:01 INFO arret
FIN
cat > config.conf <<'FIN'
# Serveur
server.port=8080
server.host=localhost
# support=off
report=daily
db.port=5432
price=10$
FIN
printf '# TODO: tester\nprint("ERROR")\n' > src/app.py
printf 'TODO: documenter\n' > src/notes.txt
printf '// TODO: lib\n' > node_modules/lib.js
}

The braces group the commands behind the &&: they only run if mkdir ~/grep-lab succeeds. If the folder already exists, nothing else is written: delete the old one (section "Clean up the practice folder"). In app.log, spot the lines that contain error in lowercase and ERROR puis ERROR, which contains the word twice. The outputs come from GNU grep 3.11, with error messages in English (they may be in another language on your machine); grep --version prints your version. Run all the commands from ~/grep-lab.

The grep command in detail

A grep command is written in this order: the options, then the pattern (the text you look for), then the files. The pattern comes before the files. Read the line from left to right: each number points to the explanation of that piece.

Anatomy of the command

Syntaxgrep [options] 'pattern' file

  1. grep the programIt looks for a text, line by line.
  2. -i the caseoptionalWith -i, upper and lower case are the same.
  3. -n the numberoptionalWritten before each line found.
  4. 'ERROR' the patternThe text to look for, in single quotes.
  5. app.log the fileoptionalWithout a file, grep reads what comes through a pipe.

Output4 lines, with their number

How grep picks lines, step by step

The map follows grep on the six lines of app.log: it reads a line, looks for the pattern and prints the whole line if the pattern is there. Two options change the choice: -i ignores the difference between uppercase and lowercase, -v keeps the lines where the pattern is missing. Before you turn them on, predict the result of grep 'ERROR' app.log: how many lines are printed? Ask the same question with -i, with -v, then with both. Then check on the map: look, line by line, at which one is printed and which one is dropped.

Mental model

How grep chooses lines

read a linelook for the patternprint the line or move on for each line of the file

$ grep 'ERROR' app.log

  1. “INFO demarrage” does not contain the pattern: grep moves on.
  2. “ERROR disque plein” contains the pattern: grep prints the whole line.
  3. “info error=0” contains error in lower case. Without -i, that is not ERROR: grep moves on, with no message.
  4. “DEBUG ping” does not contain the pattern: grep moves on.
  5. The pattern appears twice, but grep prints the line only once.
  6. “WARN error rate” contains error in lower case. Without -i, that is not ERROR: grep moves on, with no message.
  7. 2 lines printed out of 6. The exit code is 0: at least one line was found.

What the animation shows

  1. grep prints the whole line, not only the word found.
  2. Case matters: ERROR and error are two patterns, except with -i.
  3. `-v` keeps the opposite: the lines without the pattern.
  4. A line is printed only once, even if the pattern appears twice in it.

Golden rules

Put the pattern in single quotes

The shell does not change it before grep:

grep 'ERROR' app.log

Nothing comes out? Try without case

It is the first thing to check:

grep -i 'error' app.log

Essential vocabulary

Choose the lines · what is kept

-i
Ignore casegrep -i 'error' app.log → 4 lines
-v
Keep the oppositegrep -v 'ERROR' app.log → 4 lines
-w
The whole word onlygrep -w 'ERR' app.log; echo $? → code 1: ERR is not a word
^
The line starts withgrep -i '^error' app.log → 2 lines, not 4

Choose the display · what comes out

-n
The number of each linegrep -n 'ERROR' app.log → 2 and 5
-c
Count the linesgrep -c 'ERROR' app.log → 2 lines, not 3 times
-o
Only the text foundgrep -o 'ERROR' app.log → ERROR 3 times
-q
Print nothing, read the codegrep -q 'ERROR' app.log; echo $? → code 0

Find a line with grep

To find a line, you give grep a pattern and a file. It prints the whole line, not only the word it found.

Terminal window
grep 'ERROR' app.log; echo $?
Output
ERROR disque plein
ERROR puis ERROR
0

The last number is the exit code, which echo $? prints right after a command. For grep: 0 if at least one line is found, 1 if none, 2 on error.

Pattern without quotes

Before running grep, the shell transforms some characters: * and ? become file names, $ a variable, | a pipe. In a folder that holds app.log and service.log, grep *.log config.conf is read as grep app.log service.log config.conf: grep looks for the text app.log in two files, without a message. The pattern *.log disappeared before grep even started. echo grep *.log config.conf shows you what the shell passes on. Between single quotes, the shell leaves everything alone: always put the pattern in them.

Error: pattern and file swapped

With grep app.log ERROR, grep takes the first word as the pattern and the second as a file, and answers grep: ERROR: No such file or directory. The message names ERROR as a missing file: the arguments are in the wrong order. The exit code is 2, an error from grep and not "nothing found".

Nothing prints, or too many lines

Two symptoms are common: a search that finds nothing although the text is there, or a search that brings back extra lines. Three options cover these cases: -i, -v and -w.

Ignore case

By default, grep tells uppercase from lowercase: error and ERROR are two different patterns. grep 'error' app.log prints info error=0 and WARN error rate, but not the ERROR lines. When grep does not find what you are sure you saw, check the case first.

-i makes the search case-insensitive: grep -i 'error' app.log prints four lines, the two ERROR lines and the two lowercase ones. Depending on the software, the level is written ERROR, Error or error: -i keeps you from missing some.

Exclude a pattern

-v inverts the selection: grep prints the lines that do not contain the pattern. grep -v 'ERROR' app.log prints the four lines left once the two ERROR lines are removed. It is used to drop noise, for example the DEBUG lines of a chatty log.

Unwanted partial match

Without an option, grep looks for the pattern anywhere in the line, even in the middle of another word.

Terminal window
grep 'INFO' service.log
grep -w 'INFO' service.log
Output of the first command
2025-03-14 08:00:01 INFO demarrage du service
2025-03-14 08:00:02 INFORMATION version 2.4
2025-03-14 08:02:00 INFO connexion de 192.168.1.10
2025-03-14 08:02:05 INFO requete 12345 traitee
2025-03-14 08:04:01 INFO arret
Output of the second command
2025-03-14 08:00:01 INFO demarrage du service
2025-03-14 08:02:00 INFO connexion de 192.168.1.10
2025-03-14 08:02:05 INFO requete 12345 traitee
2025-03-14 08:04:01 INFO arret

-w requires a whole word: the pattern must be neither preceded nor followed by a letter, a digit or a _. The INFORMATION line disappears. Without -w, the result looked fine: a non-empty output does not prove the pattern was the right one. -x goes further and requires the whole line to be equal to the pattern.

Know where and how many

Once the line is found, you want to know where it sits in the file, or how many there are.

Number the lines

-n prefixes each line with its number in the file. grep -n 'ERROR' app.log prints 2:ERROR disque plein and 5:ERROR puis ERROR. The number, followed by :, helps you find the line in an editor or tell a colleague where to look.

-c counts lines, not occurrences

-c prints the number of lines that match, not the number of times the pattern appears. grep -c 'ERROR' app.log prints 2: two lines contain ERROR. But line 5 contains the word twice, so the file holds three occurrences. To count them, you have to print them one per line, with -o.

-o prints only the part that matches the pattern, one per line, instead of the whole line. With wc -l, which counts the lines it receives, you get the number of occurrences: grep -o 'ERROR' app.log | wc -l prints 3. -o is also used to extract a precise piece of a line.

The search that brings back too many lines Exercise 1 of 2 · ~8 min · terminal

A colleague wants to know how many port settings config.conf contains. He runs grep -c 'port' config.conf, reads the result and announces it. The number is plausible, but it is wrong. Redo his search, find the lines counted by mistake, then write the right one.

Redo, then fix the search

Run his command and print the counted lines with their number. Then drop the extra lines, count and print the ones that remain.

A hint 1 / 1

Read the lines found, not only their number: some words contain port in the middle.

I have tried: show the solution
Terminal window
grep -n 'port' config.conf
grep -nw 'port' config.conf
Outputs
2:server.port=8080
4: # support=off
6:report=daily
7:db.port=5432
2:server.port=8080
7:db.port=5432

Without -w, support and report count too, since they contain port. With -w, port has to be a word: in server.port it follows a dot, which separates words, whereas in report it is stuck to other letters.

See what happened around

An error line rarely says what caused it. -A N prints N lines after each match (After), -B N N lines before (Before), -C N N lines on each side (Context).

Show the context

With -n, the lines found carry a : after their number, and the context lines a -.

Terminal window
grep -n -B 1 'delai' service.log
grep -n -A 1 'INFORMATION' service.log
Outputs
9-2025-03-14 08:03:00 DEBUG date de sauvegarde 2025-03-13
10:2025-03-14 08:04:00 ERROR delai depasse apres 30 s
2:2025-03-14 08:00:02 INFORMATION version 2.4
3-2025-03-14 08:01:10 ERROR disque plein

-B 1 shows what comes before the error on line 10, -A 1 what comes after line 2. When several blocks are far apart in the file, grep separates them with a -- line.

Describe a pattern

A pattern can describe a shape: a line that starts with a date, a five-digit number, an address. This language is called regular expressions (regex). Without an option, grep reads basic regex; with -E, extended regex.

Basic regular expressions

^ anchors the pattern to the start of the line, $ to the end.

Terminal window
grep '2025-03-13' service.log
grep '^2025-03-13' service.log; echo $?
grep 'arret$' service.log
grep -n '^$' config.conf
Outputs
2025-03-14 08:03:00 DEBUG date de sauvegarde 2025-03-13
1
2025-03-14 08:04:01 INFO arret
5:

Without an anchor, the date of the 13th is found at the end of a line of the 14th. With ^, nothing prints: no line starts with that date. ^$ finds the empty lines, here line 5.

Two other symbols are often used. . stands for any character, and * repeats zero times or more the character before it. To try them without creating a file, printf sends four lines (separated by \n) to grep through a pipe:

Terminal window
printf 'ac\nabc\nabbc\nadc\n' | grep 'ab*c'
Output
ac
abc
abbc

ac is found: zero b is fine. This * is not the shell wildcard.

Between brackets, you list the accepted characters: [0-9] matches a digit, and [retry] matches one single character among r, e, t, y. The backslash takes away the special meaning of the bracket:

Terminal window
grep -c '[retry]' service.log
grep '\[retry\]' service.log
Outputs
11
2025-03-14 08:01:11 WARN nouvel essai [retry]

All eleven lines of the file contain one of these letters. If a search brings back almost everything, a special symbol is hiding in the pattern.

Exclude comments

\s means a blank. ^\s*# finds a # at the start of a line, preceded or not by blanks, and -v removes those lines:

Terminal window
grep -v '^\s*#' config.conf
Output
server.port=8080
server.host=localhost
report=daily
db.port=5432
price=10$

With '^#' alone, the indented comment # support=off would have stayed. \s is a GNU grep extension.

Unescaped special characters

To look for a real $, as in price=10$, the pattern alone is not enough:

Terminal window
grep 'price=10$' config.conf; echo $?
grep -F 'price=10$' config.conf
Outputs
1
price=10$

The first command looked for price=10 followed by the end of the line. -F reads the pattern as plain text, with no special symbol. Use it as soon as the text you look for contains . * [ ] $ ^, for example a file name.

Basic versus extended regex

With -E, five more symbols are written directly: | (or), + (once or more), ? (zero or once), () (group) and {n,m} (repeat n to m times). Without -E, they are ordinary characters.

Terminal window
grep 'ERROR|WARN' service.log; echo $?
grep -E 'ERROR|WARN' service.log
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' service.log
Outputs
1
2025-03-14 08:01:10 ERROR disque plein
2025-03-14 08:01:11 WARN nouvel essai [retry]
2025-03-14 08:01:12 ERROR disque plein
2025-03-14 08:04:00 ERROR delai depasse apres 30 s
192.168.1.10

Without -E, grep looked for the text ERROR|WARN, bar included. The last command extracts an IP address: three times "one to three digits then a dot", then one to three digits. It checks the shape, not the values: 999.1.1.1 would pass.

Trace back to the origin of a trace Exercise 2 of 2 · ~8 min · terminal

In service.log, one indented line starts with trace :. Find what happened just before it, extract only the name of the Python file it cites (lowercase letters, a real dot, then py), and count the errors and warnings of the minute 08:01.

See the line before

Print the trace with its number and the line before it.

Extract the name

Write a pattern that prints only the file name.

Count the minute

Keep the lines of the minute 08:01, then count those that contain one of the two levels. Two grep commands linked by a pipe will do.

A hint 1 / 1

A dot without a backslash stands for any character. One option prints only the part found.

I have tried: show the solution
Terminal window
grep -n -B 1 'trace' service.log
grep -oE '[a-z]+\.py' service.log
grep '^2025-03-14 08:01' service.log | grep -cE 'ERROR|WARN'
Outputs
5-2025-03-14 08:01:12 ERROR disque plein
6: trace : worker.py, ligne 42
worker.py
3

The trace follows the error of line 5. [a-z]+ takes the letters, \. a real dot. The ^ anchor avoids counting a date quoted elsewhere in a line.

Search a folder

The files to search are not always known in advance. grep 'TODO' . fails with grep: .: Is a directory and the code 2. With -r, grep goes down into the subfolders.

Recursive search in a project

Terminal window
grep -r 'TODO' .
Output
./src/notes.txt:TODO: documenter
./src/app.py:# TODO: tester
./node_modules/lib.js:// TODO: lib

Each line starts with the path of the file, then :. The order of the files depends on the system and may differ on yours. node_modules holds the downloaded libraries of a JavaScript project, and does not interest you: --exclude-dir skips a folder, --include keeps only the files whose name matches. To exclude several folders, write --exclude-dir={node_modules,.git} without quotes around the braces: between quotes, the shell no longer expands them and grep excludes nothing, without a message.

Terminal window
grep -r --include='*.txt' 'TODO' .
Output
./src/notes.txt:TODO: documenter

File names only

-l prints the name of each file that contains the pattern, once, without the lines. It tells you which files to edit. Here, --exclude-dir skips node_modules:

Terminal window
grep -rl --exclude-dir='node_modules' 'TODO' .
Output
./src/notes.txt
./src/app.py

Use grep in a pipe and in a script

When no file is given, grep reads what another command sends through a pipe. The pipe only passes standard output, not error messages: 2>&1 adds them.

Terminal window
ls app.log absent | grep -c 'absent'
ls app.log absent 2>&1 | grep -c 'absent'
Outputs
ls: cannot access 'absent': No such file or directory
0
1

In the first command, the message goes around the pipe: grep does not see it.

grep finds itself

ps aux lists the processes, that is, the programs that are running, with their number (PID). Start one that does nothing for five minutes (& gives the prompt back right away), then look for it. grep is a process too, and its command line contains the pattern:

Terminal window
sleep 300 &
ps aux | grep sleep
Output
lab 149 0.0 0.0 3012 1888 ? S 11:18 0:00 sleep 300
lab 152 0.0 0.0 3932 1920 ? S 11:18 0:00 grep sleep

There are two lines: your sleep 300 and the grep sleep command itself. Your user name, the PIDs and the time will differ. For a program that is not running, the trap gives a false positive: ps aux | grep nginx prints the single line of grep nginx and still returns code 0. Three commands avoid it:

  • ps aux | grep -v grep | grep sleep removes the grep line with -v;
  • ps aux | grep '[s]leep' writes [s]leep, which matches the text sleep but not its own command line;
  • pgrep -a sleep (package procps, or procps-ng on RHEL and AlmaLinux) searches among the processes without including itself and prints 149 sleep 300.

Then stop the process with kill $!, where $! is the PID of the last program started with &.

Exit codes and -q

In a script, -q suppresses the output and leaves only the exit code.

Terminal window
grep -q 'ERROR' app.log; echo $?
grep -q 'FATAL' app.log; echo $?
grep -q 'ERROR' absent.log; echo $?
Output
0
1
grep: absent.log: No such file or directory
2

If a file is missing while another one contains the pattern, grep prints the lines found but returns 2. With -q, one line found is enough for 0.

An if only knows two cases: 0, or something else. A misspelled file name therefore looks like "nothing found". Keep the code in a variable to tell the three cases apart:

Terminal window
grep -q 'ERROR' service.lgo
code=$?
if [ "$code" -eq 0 ]; then echo 'Alerte'
elif [ "$code" -eq 1 ]; then echo 'RAS'
else echo 'Lecture impossible'
fi
Output
grep: service.lgo: No such file or directory
Lecture impossible

$? changes after each command: read it right away.

Which command to choose?

grep finds text. For another need, take the tool that follows.

NeedCommand
Edit the text foundsed
Work on columnsawk
Find files by name or datefind
Search a very large code repositoryripgrep (in French)

egrep and fgrep, the old names of grep -E and grep -F, have been deprecated since GNU grep 3.8.

Troubleshooting

When grep does not return what you expect, first test the pattern on a line you control: echo 'test ERROR test' | grep 'ERROR'.

Message or symptomLikely causeSolution
Permission denied with -r (code 2)Unreadable file; the others are still readCheck the permissions; do not hide it with 2>/dev/null
Unmatched [ (code 2)Bracket opened and not closedClose the bracket, or \[, or -F
No result (code 1)Different case, regex without -ETry -i, add -E for |, +, ?, ()
ERROR$ finds nothing (code 1)File from Windows: an invisible carriage return ends the lineSee "File from Windows"
binary file matches (code 0)File detected as binary, lines not printedSee "Binary files skipped"

File from Windows

A file created on Windows ends its lines with an invisible carriage return. grep 'ERROR$' finds nothing, because the last character is not R. cat -A makes hidden characters visible, and sed removes the carriage return before the filter:

Terminal window
printf 'ERROR\r\n' > dos.log
grep 'ERROR$' dos.log; echo $?
cat -A dos.log
sed 's/\r$//' dos.log | grep 'ERROR$'
Outputs
1
ERROR^M$
ERROR

^M is the carriage return, right before the $ that marks the end of the line. dos.log is not modified.

Binary files skipped

grep detects a binary file (a null byte is enough) and writes grep: fichier.bin: binary file matches on standard error instead of the lines, with code 0. With 2>/dev/null, the message disappears and the command seems to have found nothing. -a forces processing as text:

Terminal window
printf 'texte\0octet-nul motif\n' > fichier.bin
grep 'motif' fichier.bin
grep -a 'motif' fichier.bin | cat -v
Outputs
grep: fichier.bin: binary file matches
texte^@octet-nul motif

cat -v makes the null byte visible as ^@.

Clean up the practice folder

When you are done, delete the practice folder.

Terminal window
cd ~
rm -r ~/grep-lab

Key points

  • grep prints the whole lines that contain the pattern. Put the pattern between single quotes and before the files.
  • Its exit code is 0 if a line matches, 1 if none does, 2 on error (with -q, one line found is enough for 0).
  • -i ignores case, -v inverts the selection, -w requires the whole word. A non-empty output does not prove the pattern was the right one.
  • -n numbers the lines, -c counts lines, -o followed by wc -l counts occurrences, -A, -B and -C add the neighboring lines.
  • Without an option, grep reads basic regex: |, +, ?, () and {} need -E, and text read as is needs -F.
  • -r walks a folder, --include and --exclude-dir set its scope, -l prints only the names. ps aux | grep name finds its own line: prefer pgrep -a name.

Knowledge check

Check that the essentials of this guide are acquired. The questions only cover what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer