grep – File pattern searcher

Syntax

grep {option} {parameter} {flag} [pattern] {file}

The grep utility (global / regular expression / print) searches any given input file, selecting the lines that match one or more search patterns. Zero or more input files can be passed. If no file is specified, then the standard input is used.

The grep utility exits with one of the following values:

  • 0 if one or more lines were selected
  • 1 if no lines were selected
  • >1 if an error occurred

Options include

-E, --extended-regexp
Interpret the pattern as an extended regular expression.
-n, --line-number
Each output line is preceded by its relative line number in the file, starting at line 1. The line number counter is reset for each file processed.
-o, --only-matching
Prints only the matching part of the lines.
-R, -r, --recursive
Search recursively also in any subdirectory of the path given.
-v, --invert-match
The lines which are not matching any of the specified patterns are selected.

Parameters include

--context[=number]
Print number lines of leading and trailing context. The default is 2.

Flags include

--exclude
Excludes files matching the given filename pattern from the search. Patterns are matched to the full path specified, not only to the filename component.
Note that --exclude patterns take priority over --include patterns; if no --include pattern is specified, then all files are searched that are not excluded.
--exclude-dir
If -R is specified, then it excludes directories matching the given filename pattern from the search.
Note that --exclude-dir patterns take priority over --include-dir patterns; if no --include-dir pattern is specified, then all directories are searched that are not excluded.
--include
Only files matching the given filename pattern are searched. Patterns are matched to the full path specified, not only to the filename component.
Note that --exclude patterns take priority over --include patterns.
--include-dir
If -R is specified, then only directories matching the given filename pattern are searched.
Note that --exclude-dir patterns take priority over --include-dir patterns.

Example

# extract and verify the BagIt version from the 'bagit.txt' file

grep 'BagIt-Version:' < 'bagit.txt' | grep -o -E '0.9[3-7]|1.0'

# or a little shorter

grep 'BagIt-Version:' < 'bagit.txt' | grep -oE '0.9[3-7]|1.0'

Further information

man grep


2022-03-26