> For the complete documentation index, see [llms.txt](https://gitbook.nicacton.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.nicacton.com/cloud-computing/red-hat/rhel/grep-and-regex.md).

# Grep & Regex

## Grep

A program for finding matching patterns. Follows `$ grep <pattern> <file>` or as part of a pipe: `$ find . -name *.txt | grep taxes`

Common Flags:

* -i : makes it case insensitive
* -r : makes the search recursive (searches directories)
* -v : makes the search find all instances where there is not a pattern match
* -w : makes the search match on a word rather than any pattern match

## Regular Expressions (Regex)

Regex is passed into grep like so `grep '<expression>' file`

* `^` - match expression at the start of a line, as in `^A`
* `$` - match expression at the end of a line
* `\` - Turn off the special meaning of the next character and treat it as a string, as in `\*` or `\^`
* `[ ]` - Match any one of the enclosed characters, as in `[aeiou]` or a range like `[0-9]` or `[a-zA-Z]`
* `[^ ]` - Match any one character except those enclosed in `[ ]` as in `[^0-9]`
* `.` Match a single character of any value except EOL
* `*` - Match zero or more of the preceding character or expression
* `\{x,y\}` - Match x to y occurences of the preceding
* `\{x\}` - Match exactly x occurrences of the preceding
* `\{x,\}` - Match x or more occurences of the preceding

#### Grep Examples

* `grep linux files` - Search files for lines with the word linux
* `grep '^linux' files` with linux at the start of a line
* `grep 'linux$' files` with linux at the end of a line
* `grep '^linux$' files` with lines containing only linux
* `grep '\^s' files` lines starting with ^s (\ is an escape for that character)
* `grep '[Ll]inux' files` search for either Linux or linux
* `grep 'B[oO][bB]' files` search for BOB, Bob, BOb or BoB
* `grep '^$' files` search for blank files
* `grep '[0-9][0-9]' files` search for pairs of numeric digits
