https://www.linode.com/docs/guides/how-to-grep-for-text-in-files/

Search and filter text with Grep

Grep is a command-line utility that can search and filter text using a common regular expression syntax. It is so ubiquitous that the verb “to grep” has emerged as a synonym for “to search.” grep is a useful tool for finding all occurrences of a search term in a selection of files, filtering a log file or stream, or as part of a script or chain of commands.

This guide provides an overview of grep usage, a brief introduction to regular expression syntax, and practical examples.

Using Grep

This guide references recent versions of GNU grep, which are included by default in all images provided by Linode. It is also provided as part of the common base selection of packages provided in nearly all distributions of Linux-based operating systems.

The Grep Command

A basic grep command uses the following syntax:

grep "string" ~/threads.txt

The first argument to grep is a search pattern. The second (optional) argument is the name of a file to be searched. The above sequence will search for all occurrences of “string” in the ~/threads file.

If you want to search multiple files, the -r flag enables recursive searching through a directory tree:

grep -r "string" ~/thread/

When used on a specific file, grep only outputs the lines that contain the matching string. When run in recursive mode, grep outputs the full path to the file, followed by a colon, and the contents of the line that matches the pattern. Patterns in grep are, by default, basic regular expressions. If you need a more expressive regular expression syntax, grep is capable of accepting patterns in alternate formats with the following flags:

Untitled

Grep provides a number of powerful options to control its output:

Untitled

Piping Command Outputs to grep

In addition to reading content from files, grep can read and filter text from standard input. The output of any command or stream can be piped to the grep command. Then, grep filters this output according to the match pattern specified and outputs only the matching lines. For instance, given the following command:

ls --help | grep "dired"