Grep and RegEx

less than 1 minute read

Overview

grep = designed for finding matching patterns usage: grep pattern file options

e.g. find . -name \*.txt | grep taxes -i

Options

-i = case insensitive -r = recursive through directories -v = finds all instances of no pattern match -w = serches for single word and not just any instance

Examples

To find the pattern ‘taxes’ recursively $ grep taxes * -ri The star looks at all files in the current directory

To find all occurrences of the word `patricia’ in a file:

$ grep 'patricia' myfile

To find all occurrences of the pattern `.Pp’ at the beginning of a line:

$ grep '^\.Pp' myfile

The apostrophes ensure the entire expression is evaluated by grep instead of by the user’s shell. The caret \^ matches the null string at the beginning of a line, and the \ escapes the ‘.’, which would otherwise match any character.

To find all lines in a file which do not contain the words foo' or bar’:

$ grep -v -e 'foo' -e 'bar' myfile

Categories:

Updated: