DEV Community

Cover image for Find Matching Lines in a File with grep
Labby for LabEx

Posted on Originally published at labex.io

Find Matching Lines in a File with grep

Originally published on LabEx Blog.

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
Enter fullscreen mode Exit fullscreen mode

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

grep 'Mochi' orders.txt
Enter fullscreen mode Exit fullscreen mode

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

09:00 Mochi tea
09:10 Mochi cocoa
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
1:09:00 Mochi tea
3:09:10 Mochi cocoa
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)