Searching Text with grep
Introduction: Searching Text with grep
So far in this course, you've read files from start to finish with cat or head. That's fine for a five-line log, but real files can run to thousands of lines, and you rarely want all of them — you want the one line that mentions an error or every line about a specific user. grep is the command built for exactly that: It searches text and prints back only what matches.
This lesson has two halves. The first is about shaping the question — what counts as a match. The second is about shaping the answer — what grep hands back once it finds something. By default, grep reads its pattern as a basic regular expression, which means characters like ., *, [, ^, and $ carry special meaning rather than standing for themselves. Every pattern in this lesson is made of plain letters only, with none of those metacharacters, so each one behaves exactly like literal text. When you need a pattern treated as a fixed literal string no matter what characters it contains, grep -F guarantees that. grep comes pre-installed on macOS, Linux, and your CodeSignal environment, so there's nothing to set up.
Your First Search
The most basic way to run grep follows a simple shape: grep PATTERN FILE. grep opens the file, checks every line against that pattern, and prints only the lines where it finds a match. Because the patterns below contain no regular-expression metacharacters, "match" here means finding that exact sequence of characters somewhere in the line. A line with no match never appears in the output at all — grep is a filter, not a highlighter, so it either lets a line through or drops it silently.
This one command replaces a lot of manual searching. Instead of opening a huge log in cat and scrolling with your eyes, you tell grep exactly what string you're hunting for, and it hands back only the relevant lines. That's the whole point of the tool: turning "read everything and look for X" into "show me only the lines with X."
Let's set up a small practice file to search. First, make a folder for it:
Then move into it:
Now write the file:
This is the same heredoc technique from Lesson 1 — it writes five lines straight into app.log. Notice the deliberate mix of capitalizations of the word "error" across those lines, plus one line where "errors" shows up as part of a longer word. That mix is exactly what will make the flags in the following sections worth learning.
Let's search for a plain literal string, asking for line numbers with -n:
grep ERROR app.log on its own would have printed just the matching line's text, with no way to tell which line it came from. Adding -n prefixes every match with its position in the file — here, 4: — so you know exactly where to look. Only line 4 matched because grep is case-sensitive by default: The lowercase error on line 2 and the errors on line 5 don't count as matches for the exact string ERROR.
