How to extract text by keyword using grep in Linux

This article provides a complete guide on how to extract text by keyword using grep, including how to use grep to extract text from files, directories, and even the live output of other commands.

Extracting Text by Keyword grep

  • Prints lines of files or STDIN where a pattern is matched.
grep 'john' /etc/passwd
date --help | grep year
  • Use -i to search case-insensitively.
  • Use -n to print line numbers of matches.
  • Use -v to print lines not containing pattern.
  • Use -Ax to include the x lines after each match.
  • Use -Bx to include the x lines before each match.
  • Use -r to recursively search a directory.
  • Use –color to highlight the match in color.

grep displays the lines in a file that match a pattern. It can also process standard input. The pattern may contain regular expression metacharacters and so it is considered good practice to always quote your regular expressions.

Examples: –

To list lines containing either “Cat” or “cat” from the pets file

grep '[Cc]at' pets

To list only lines of output from ps, which lists running processes, that contain the string “init”: from the ps command

ps ax | grep 'init'

Common grep options include:

-v: – return lines that do not contain the pattern
-n: – precede returned lines with line numbers
-c: – only return a count of lines with the matching pattern
-I: – only return the names of files that have at least one line containing the pattern
-r: – perform a recursive search of files, starting with the named directory
-i: – perform a case-insensitive search
-B, -A: – When followed by a number, these options print that many lines before or after each match. this is useful for seeing the context in which a match appears within a file.

To change the color that –color uses (red by default), use the GREP_COLOR variable:

export GREP_COLOR='01;34'

Read the dir_colores(5) man page, or look at the /etc/DIR_COLORS for more informaiton and examples.

Leave a Comment