← Linux and the Command Line
Lesson 18 of 51 · 10 XP
grep — searching text
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
grep prints the lines that match a pattern:
grep error app.log # lines with the word error
grep -i error app.log # ignoring case (ERROR, Error)
grep -v debug app.log # lines WITHOUT a match (invert)
grep -n TODO main.c # with line numbers
grep -c 404 access.log # only the number of matching lines
grep -r "password" /etc # recursively through all the files of a folder
grep -w is text.txt # a whole word: finds is, but not this
grep -E "cat|dog" pets.txt # extended regular expressions: | + ? ()
The pattern is a regular expression:
^abc |
the line starts with abc |
abc$ |
ends with abc |
. |
any character |
[0-9] |
a digit |
a* |
zero or more as |
grep "^#" config.conf # only the comments
grep -v "^#" config.conf | grep -v "^$" # without comments and empty lines
Task. The input is a web server log: each line has a method, a path and a response code. Print the lines with 4xx and 5xx error codes (the last field starts with 4 or 5), and on the last line — how many there are.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.