Skip to main content

The grep Command: Find Lines of Text in Files on Linux

The grep command reads text and shows each line that contains a word or pattern you pick. Linux users search log files, settings files and source code with it every day. This guide covers what it does, the options you will use most, and how GNU grep works internally.

What it does

A lot of what a computer knows is stored as plain text. Settings, error reports and program code often live in text files. Some of them run to thousands of lines, and reading them by eye is slow.

grep is a small program that does the searching for you. You give it a word, and it shows every line where that word appears. It never changes your files. It only reads them and reports what it found.

Picture a librarian with a pile of letters. You ask for every line that mentions the word "invoice", and the librarian reads each letter and copies out only those lines. That is what grep does. The comparison has one limit: grep reads text only, so it cannot find words inside photos or scanned pages.

People who use Linux only through apps and menus may never type grep at all. Once you open a terminal (the text window where you type commands), it becomes one of the most useful tools to learn.

Here is a very simple example: grep hello notes.txt shows every line in the file notes.txt that contains "hello".

You only need to act if you want to start using the terminal. Most versions of Linux use the same edition of the program, called GNU grep, so the examples in this guide work on them.

Back to top

How to use it

You type grep, then a pattern, then one or more files. Put the pattern in quotes. That way the shell does not change it before grep sees it.

grep -i 'hello.*world' menu.h main.c

This looks in two files for "hello" with "world" somewhere after it, and -i makes upper and lower case count as the same.

grep -w 'hello' example.txt

With -w, only whole words match, so a line that says "Othello" stays hidden.

grep -n -C 2 'hello' example.txt

Here -n adds line numbers, and grep prints two lines before and after each match, with -- between the groups.

grep -F "exact.string" example.txt

The -F option reads the pattern as plain text, so the dot is just a dot and not a special character.

grep -rI "pattern" directory

This searches every file below directory and skips binary files such as programs and images.

grep -r 'hello' directory --include='*.c'

With --include, a recursive search only looks at files whose names fit the pattern, in this case C source files.

grep -l 'main' test-*.c

The -l option lists only the names of files that contain a match, without the lines.

ps -ef | grep '[c]ron'

This lists running processes and keeps only the cron lines. Thanks to the brackets, grep does not match its own command line.

Some other options are worth knowing:

  • -v shows the lines that do not match.
  • -c counts the matching lines in each file.
  • -o prints only the matched text, not the full line.
  • -E turns on extended regular expressions; combine it with -i as grep -Ei.
  • -e -pattern or -- -pattern searches for text that starts with a dash.

If you search several files, grep puts the file name in front of each line by default. -H always shows it, and -h hides it.

All of these examples are for GNU grep, which works the same on any Linux distribution. There are no differences between Debian, Fedora, Arch or openSUSE here.

Back to top

How it works

grep takes its input one line at a time and tests each line against the pattern. Since the line is the unit of work, a pattern can never match a newline character. With no file argument, a normal search reads standard input, while a recursive search starts in the working directory. This article covers GNU grep, and the current man page describes version 3.12.

Pattern syntax

There are four pattern types. -G selects basic regular expressions (BRE), which is the default. -E selects extended regular expressions (ERE), and -F uses fixed strings. -P selects Perl-compatible regular expressions (PCRE), but only when grep was built with PCRE support.

In GNU grep, BRE and ERE can express the same things. GNU BRE also accepts \?, \+ and \|, which behave like ?, + and | in ERE.

Some useful escapes: \< and \> mark the start and end of a word, and \b marks a word boundary. \w equals [_[:alnum:]], and \W is its negation. Unlike in Perl, \d under -P matches ASCII digits only.

Exit status and scripts

The exit status is 0 when grep selects at least one line, 1 when it selects none, and 2 on an error. With -q, grep prints nothing and exits with 0 at the first match, even if an error also happened. That makes -q the right choice for if tests in shell scripts. Add -s to hide messages about missing or unreadable files.

grep can stop reading early, for example with -q. The command that feeds it may then get a broken pipe. --line-buffered flushes output after every line, but it can slow grep down.

Binary files and NUL bytes

If a binary file matches, grep prints a "binary file matches" message rather than the lines. -a treats binary files as text, and -I treats them as non-matching. -z ends lines with NUL bytes instead of newlines, so one match can span several text lines. -Z prints a NUL after each file name, which keeps unusual names safe in pipelines.

Locale and performance

Outside the C locale, the behavior of ranges such as [a-z] is unspecified. grep checks LC_ALL first, then the category variable, then LANG. Setting LC_ALL=C brings back the traditional behavior and is very efficient.

In other locales, case-insensitive searches and bracket expressions can be slow. Large {n,m} repeat counts use a lot of memory. Back-references can be very slow.

Under -P, the (?s) flag mostly does nothing, because grep works one line at a time. Together with -z it can work, but grep may then load the whole file into memory.

Recursion and context

-r follows symbolic links only when you name them on the command line, while -R follows all of them. The context options -A, -B and -C do nothing together with -o, and grep warns about that mix.

egrep and fgrep

egrep and fgrep are old names for grep -E and grep -F. POSIX marked them obsolescent in 1992 and removed them in 2001. GNU grep has warned about them since version 3.8 in 2022, and they are planned for removal. Write grep -E and grep -F in new scripts.

Still unclear:

  • Other versions, such as BSD and BusyBox grep, may differ in some options. This article does not cover them.
Back to top

Sources

  1. grep(1) - Linux manual page — man7.org
  2. GNU Grep manual — gnu.org
  3. tldr grep page — tldr-pages (GitHub)
Back to top
Peter Martin
Linux admin, PHP dev and Joomla specialist

Open-source enthusiast since 2005 and co-founder of Linux Nijmegen (Netherlands), passionate about solving technical challenges and sharing knowledge.

Frequently asked questions

The grep command searches through text files and shows you every line that contains a word or pattern you specify. It does not change the original files.

grep reads text files line by line to find the patterns you request. It does not read the entire file at once, which is useful for large files.

Using quotes around the pattern prevents the shell from changing it before grep sees it, ensuring the command works correctly with the intended pattern.

If grep doesn't find any lines matching the pattern, it will not produce any output. It returns an exit status of 1.