← Back to all posts

Find Matching Lines in a File with grep

Search a small text file with grep, retain original line numbers, and check case-sensitive matches.

A magnifying glass representing a search for matching lines

A three-line order file contains two orders for Mochi. Instead of reading a long file line by line, grep can print the lines that contain a pattern. The result is a selection of lines; it does not edit the file.

This LabEx video follows one search from the original file to the terminal output. You can reproduce the example in a disposable directory.

The order file and terminal show that the first and third lines match Mochi

Create and inspect the file

Run these commands in a directory you own:

mkdir -p ~/grep-demo
cd ~/grep-demo
printf '%s\n' '09:00 Mochi tea' '09:05 Luna coffee' '09:10 Mochi cocoa' > orders.txt
cat orders.txt

The file now has three lines. Search for the name with:

grep 'Mochi' orders.txt

The output contains the two full lines with Mochi, in their original order:

09:00 Mochi tea
09:10 Mochi cocoa

The quoted argument is the search pattern, and orders.txt is the input file. grep searches file contents, not filenames. The name Mochi is an ordinary pattern here; in general, grep patterns can include regular-expression characters. For literal text containing such characters, GNU grep offers -F.

Keep the original line numbers

Add -n when you need to find the matches again in the source file:

grep -n 'Mochi' orders.txt
1:09:00 Mochi tea
3:09:10 Mochi cocoa

The numbers refer to lines in the input, not positions in the filtered output. Run cat orders.txt again: the Luna line remains in the file.

Try a different spelling

Search for Luna and then lowercase mochi:

grep 'Luna' orders.txt
grep 'mochi' orders.txt

The first command prints the second order. The second prints no matching line because the default search is case-sensitive. No output from this example means the pattern did not match; a missing or unreadable file is a different situation and produces an error. GNU grep documents its matching options and exit status.

To practice the same kind of search with log messages, try LabEx’s grep command lab. Its basic search and case-insensitive steps build on this example; the lab’s -i option extends the video’s default case-sensitive search.