grep – File pattern searcher

Syntax

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

The grep utility searches any given input files, selecting lines that match one or more patterns.

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
  • >1if an error occurred

Options

-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

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

Flags

--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.

Examples

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

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

2020–07–28