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
grepin 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".
mkdir ~/grep-lab && cd ~/grep-lab && {mkdir src node_modules
cat > app.log <<'FIN'INFO demarrageERROR disque pleininfo error=0DEBUG pingERROR puis ERRORWARN error rateFIN
cat > service.log <<'FIN'2025-03-14 08:00:01 INFO demarrage du service2025-03-14 08:00:02 INFORMATION version 2.42025-03-14 08:01:10 ERROR disque plein2025-03-14 08:01:11 WARN nouvel essai [retry]2025-03-14 08:01:12 ERROR disque plein trace : worker.py, ligne 422025-03-14 08:02:00 INFO connexion de 192.168.1.102025-03-14 08:02:05 INFO requete 12345 traitee2025-03-14 08:03:00 DEBUG date de sauvegarde 2025-03-132025-03-14 08:04:00 ERROR delai depasse apres 30 s2025-03-14 08:04:01 INFO arretFIN
cat > config.conf <<'FIN'# Serveurserver.port=8080server.host=localhost # support=off
report=dailydb.port=5432price=10$FIN
printf '# TODO: tester\nprint("ERROR")\n' > src/app.pyprintf 'TODO: documenter\n' > src/notes.txtprintf '// 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
grep-i-n'ERROR'app.log -
grepthe programIt looks for a text, line by line. -
-ithe caseoptionalWith-i, upper and lower case are the same. -
-nthe numberoptionalWritten before each line found. -
'ERROR'the patternThe text to look for, in single quotes. -
app.logthe fileoptionalWithout a file,grepreads 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
Try Input · app.log
Search, then decide
Current line
$ grep 'ERROR' app.log
- “INFO demarrage” does not contain the pattern: grep moves on.
- “ERROR disque plein” contains the pattern: grep prints the whole line.
- “info error=0” contains error in lower case. Without -i, that is not ERROR: grep moves on, with no message.
- “DEBUG ping” does not contain the pattern: grep moves on.
- The pattern appears twice, but grep prints the line only once.
- “WARN error rate” contains error in lower case. Without -i, that is not ERROR: grep moves on, with no message.
- 2 lines printed out of 6. The exit code is 0: at least one line was found.
What the animation shows
- grep prints the whole line, not only the word found.
- Case matters:
ERRORanderrorare two patterns, except with-i. - `-v` keeps the opposite: the lines without the pattern.
- 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.logNothing comes out? Try without case
It is the first thing to check:
grep -i 'error' app.logEssential vocabulary
Choose the lines · what is kept
-i- Ignore case
grep -i 'error' app.log→ 4 lines -v- Keep the opposite
grep -v 'ERROR' app.log→ 4 lines -w- The whole word only
grep -w 'ERR' app.log; echo $?→ code 1: ERR is not a word ^- The line starts with
grep -i '^error' app.log→ 2 lines, not 4
Choose the display · what comes out
-n- The number of each line
grep -n 'ERROR' app.log→ 2 and 5 -c- Count the lines
grep -c 'ERROR' app.log→ 2 lines, not 3 times -o- Only the text found
grep -o 'ERROR' app.log→ ERROR 3 times -q- Print nothing, read the code
grep -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.
grep 'ERROR' app.log; echo $?ERROR disque pleinERROR puis ERROR0The 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.
grep 'INFO' service.loggrep -w 'INFO' service.log2025-03-14 08:00:01 INFO demarrage du service2025-03-14 08:00:02 INFORMATION version 2.42025-03-14 08:02:00 INFO connexion de 192.168.1.102025-03-14 08:02:05 INFO requete 12345 traitee2025-03-14 08:04:01 INFO arret2025-03-14 08:00:01 INFO demarrage du service2025-03-14 08:02:00 INFO connexion de 192.168.1.102025-03-14 08:02:05 INFO requete 12345 traitee2025-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.
Print only the match
-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
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.
- grep -c
- grep -n
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
grep -n 'port' config.confgrep -nw 'port' config.conf2:server.port=80804: # support=off6:report=daily7:db.port=54322:server.port=80807:db.port=5432Without -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 -.
grep -n -B 1 'delai' service.loggrep -n -A 1 'INFORMATION' service.log9-2025-03-14 08:03:00 DEBUG date de sauvegarde 2025-03-1310:2025-03-14 08:04:00 ERROR delai depasse apres 30 s2:2025-03-14 08:00:02 INFORMATION version 2.43-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.
grep '2025-03-13' service.loggrep '^2025-03-13' service.log; echo $?grep 'arret$' service.loggrep -n '^$' config.conf2025-03-14 08:03:00 DEBUG date de sauvegarde 2025-03-1312025-03-14 08:04:01 INFO arret5: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:
printf 'ac\nabc\nabbc\nadc\n' | grep 'ab*c'acabcabbcac 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:
grep -c '[retry]' service.loggrep '\[retry\]' service.log112025-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:
grep -v '^\s*#' config.confserver.port=8080server.host=localhost
report=dailydb.port=5432price=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:
grep 'price=10$' config.conf; echo $?grep -F 'price=10$' config.conf1price=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.
grep 'ERROR|WARN' service.log; echo $?grep -E 'ERROR|WARN' service.loggrep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' service.log12025-03-14 08:01:10 ERROR disque plein2025-03-14 08:01:11 WARN nouvel essai [retry]2025-03-14 08:01:12 ERROR disque plein2025-03-14 08:04:00 ERROR delai depasse apres 30 s192.168.1.10Without -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
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.
- grep -n
- grep -B
- grep -o
- grep -E
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
grep -n -B 1 'trace' service.loggrep -oE '[a-z]+\.py' service.loggrep '^2025-03-14 08:01' service.log | grep -cE 'ERROR|WARN'5-2025-03-14 08:01:12 ERROR disque plein6: trace : worker.py, ligne 42worker.py3The 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
grep -r 'TODO' ../src/notes.txt:TODO: documenter./src/app.py:# TODO: tester./node_modules/lib.js:// TODO: libEach 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.
grep -r --include='*.txt' 'TODO' ../src/notes.txt:TODO: documenterFile 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:
grep -rl --exclude-dir='node_modules' 'TODO' ../src/notes.txt./src/app.pyUse 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.
ls app.log absent | grep -c 'absent'ls app.log absent 2>&1 | grep -c 'absent'ls: cannot access 'absent': No such file or directory01In 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:
sleep 300 &ps aux | grep sleeplab 149 0.0 0.0 3012 1888 ? S 11:18 0:00 sleep 300lab 152 0.0 0.0 3932 1920 ? S 11:18 0:00 grep sleepThere 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 sleepremoves thegrepline with-v;ps aux | grep '[s]leep'writes[s]leep, which matches the textsleepbut not its own command line;pgrep -a sleep(packageprocps, orprocps-ngon RHEL and AlmaLinux) searches among the processes without including itself and prints149 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.
grep -q 'ERROR' app.log; echo $?grep -q 'FATAL' app.log; echo $?grep -q 'ERROR' absent.log; echo $?01grep: absent.log: No such file or directory2If 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:
grep -q 'ERROR' service.lgocode=$?if [ "$code" -eq 0 ]; then echo 'Alerte'elif [ "$code" -eq 1 ]; then echo 'RAS'else echo 'Lecture impossible'figrep: service.lgo: No such file or directoryLecture impossible$? changes after each command: read it right away.
Which command to choose?
grep finds text. For another need, take the tool that follows.
| Need | Command |
|---|---|
| Edit the text found | sed |
| Work on columns | awk |
| Find files by name or date | find |
| Search a very large code repository | ripgrep (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 symptom | Likely cause | Solution |
|---|---|---|
Permission denied with -r (code 2) | Unreadable file; the others are still read | Check the permissions; do not hide it with 2>/dev/null |
Unmatched [ (code 2) | Bracket opened and not closed | Close the bracket, or \[, or -F |
| No result (code 1) | Different case, regex without -E | Try -i, add -E for |, +, ?, () |
ERROR$ finds nothing (code 1) | File from Windows: an invisible carriage return ends the line | See "File from Windows" |
binary file matches (code 0) | File detected as binary, lines not printed | See "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:
printf 'ERROR\r\n' > dos.loggrep 'ERROR$' dos.log; echo $?cat -A dos.logsed 's/\r$//' dos.log | grep 'ERROR$'1ERROR^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:
printf 'texte\0octet-nul motif\n' > fichier.bingrep 'motif' fichier.bingrep -a 'motif' fichier.bin | cat -vgrep: fichier.bin: binary file matchestexte^@octet-nul motifcat -v makes the null byte visible as ^@.
Clean up the practice folder
When you are done, delete the practice folder.
cd ~rm -r ~/grep-labKey points
grepprints 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). -iignores case,-vinverts the selection,-wrequires the whole word. A non-empty output does not prove the pattern was the right one.-nnumbers the lines,-ccounts lines,-ofollowed bywc -lcounts occurrences,-A,-Band-Cadd the neighboring lines.- Without an option,
grepreads basic regex:|,+,?,()and{}need-E, and text read as is needs-F. -rwalks a folder,--includeand--exclude-dirset its scope,-lprints only the names.ps aux | grep namefinds its own line: preferpgrep -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
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
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: jq: process JSON on the command line
A new full quiz with random questions
Work again only on the questions you missed