Finding text with grep
Quick answer
grep selects lines containing a match. Use it to find a message in a log without opening the whole file. Start with fixed strings for literal text, then use regular expressions for patterns.
Prepare the practice environment
Use the chapter fixture described in lab-fixtures/search-transform/README.md. Run setup as a normal user in a disposable Linux environment, enter the printed directory and check pwd. Every example assumes a fresh fixture. Commands omit the terminal prompt; outputs below are not commands.
How it works
Use grep [options] pattern file. -F treats the pattern literally; -n includes line numbers; -i ignores case according to the locale; -v selects nonmatching lines. GNU grep normally returns 0 for a match, 1 for no match, and 2 for an error (without -q). A match is not necessarily a whole word. Quote the pattern to prevent shell expansion; use -e when a pattern starts with a dash.
No printed lines can have two different explanations: the pattern did not match a readable file, or the file could not be read. For ordinary GNU grep without -q, status 1 means no selection and status 2 means an error. When diagnosing logs, do not report an empty result as evidence of a healthy system until you have checked the status.
Try the examples
Two lines match, with their original line numbers.
Expected stdout:
2:ERROR disk full4:ERROR retryThe dot is literal in fixed-string mode.
Expected stdout:
a.bNo line was printed by grep; $? immediately captures its no-match status.
Expected stdout:
status=1Common mistakes
Do not interpret every nonzero grep status as a broken command. Avoid printing unknown binary data or private logs; use the provided synthetic file.
Practice
Find INFO lines with line numbers, then search for a word that is absent and explain the status. Expected INFO lines: 1 and 3.
Related references
Study: grep. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Finding text with grep — Knowledge Check
Apply the lesson concepts to the controlled text fixture.
Which option treats a dot literally?
What does status 1 normally mean?
Which option displays line numbers?
Why quote a search pattern?