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 linuxgrep '^linux' files
with linux at the start of a linegrep 'linux$' files
with linux at the end of a linegrep '^linux$' files
with lines containing only linuxgrep '\^s' files
lines starting with ^s (\ is an escape for that character)grep '[Ll]inux' files
search for either Linux or linuxgrep 'B[oO][bB]' files
search for BOB, Bob, BOb or BoBgrep '^$' files
search for blank filesgrep '[0-9][0-9]' files
search for pairs of numeric digits
Last updated
Was this helpful?