Filter Lines Containing a String with Grep

Learn how to filter lines containing a string in Linux with grep, including basic pattern matching and practical command-line examples.

Direct answer

In a Linux or Unix shell, the standard way to filter lines containing a string is to pass the text through grep with the desired pattern. The command reads input line by line and prints only the lines that match, so it acts as a line filter rather than modifying the original file.

Basic command format

The general form is to provide a pattern and an input source. When the input source is a file, grep reads that file directly. When no file is supplied, grep reads from standard input, which allows it to filter output from another command.

grep 'string' file
command | grep 'string'

The quoted pattern is a plain string in the simplest case. Quoting is useful because it prevents the shell from interpreting spaces or special characters before grep receives them.

What filter lines means here

In this context, filtering lines means selecting the subset of input lines that contain a specified string and discarding the rest. Matching is based on the content of each complete line by default. A line qualifies if the pattern appears anywhere in that line, not only at the beginning.

Filtering files

To filter the contents of a file, place the filename after the pattern. grep prints matching lines while leaving the file unchanged. For example, a command such as grep 'error' logfile.txt returns only log lines that contain error.

Filtering command output

A pipe sends one command's output into grep as standard input. This is useful for narrowing large output sets. The command on the left produces lines, and grep retains only those containing the requested string.

ps aux | grep 'nginx'

This prints process lines that mention nginx. The same approach applies to any command whose output should be reduced to matching lines.

Operating principle and scope

grep performs pattern-based selection on a line stream. It is not an editor and does not change the input unless output is redirected to another file. The examples here cover the documented general behavior of grep for filtering lines by a literal string; pattern syntax and display options are separate topics.

Practical notes

  • Use quotes around patterns containing spaces or shell special characters
  • Matching is case-sensitive by default for a literal string
  • grep returns the whole matching line, not just the matched portion
  • Input can be a named file or standard input from a pipe

These points follow from how grep processes line-based input. The article does not make claims about specific grep versions or performance measurements beyond this general behavior.