How to Search Files for Text with the Linux grep Command
The grep command finds lines that contain a pattern. Give it a search term and a file, and it prints every matching line: grep error app.log. You can also pipe the output of any command into grep to filter it. This guide covers the options you will use most.
The basic grep syntax
The first argument is the text to find, the rest are files to search. grep prints the file name when you search several files at once.
Ignore case with -i
Searches are case-sensitive by default, so Error and ERROR do not match error. Add -i to find all of them at once.
Search recursively with -r
To search a whole directory tree, use -r. It descends into subdirectories and is the command most people use to find where a setting or function appears in a project.
Show line numbers and whole words
Line numbers make results easy to jump to in an editor. Combine them with -w to match a whole word, so cat does not match catalog.
Count matches and filter command output
Use -c to count matching lines instead of printing them. grep becomes even more useful when you pipe command output into it with pipes.
For more precise matching, grep understands regular expressions. See the grep reference for the full option list.
Keep learning
Related guides: How to Use the sed Command for Text Editing · awk: The Linux Text Processing Tool Explained · Linux Redirection and Pipes: A Practical Guide. Read all tutorials on the Learn Linux blog.