Skip to content

Instantly share code, notes, and snippets.

@innyso
Last active May 5, 2021 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save innyso/251d51bfb5efa82032d79f96de67879f to your computer and use it in GitHub Desktop.
Save innyso/251d51bfb5efa82032d79f96de67879f to your computer and use it in GitHub Desktop.
#linux #cmd #grep #regex

Difference between grep with and without extended-regex

  • by default grep interpret search pattern as basic regular expression i.e. the meta-characters ?, +, |, ( and ) are interpreted as literal, hence need to escape with backslash
  • can pass in extended regular expresson option -E (or --extended-regex) which means it doesn't take the meta-characters literally hence do not need to escape with backslash

Anchoring

# a line begins with hello
grep '^hello' world.txt 

# a line ends with hello
grep 'hello$' world.txt

Single Character

# match anything begin with hello then 3 characters and ends with world
grep 'hello..world' sample.txt

Bracket Expression


# matches duck or dunk
grep 'du[cn]k' sample.txt

# do not include characters in bracket. 
# will match log lag but not leg
grep 'l[^e]g' sample.txt

# match a range of characters
# will match file-1..9
grep 'file-[1-9]' sample.txt
pre-defined characters
Quantifier Character Classes
[:alnum:] Alphanumeric characters.
[:alpha:] Alphabetic characters.
[:blank:] Space and tab.
[:digit:] Digits.
[:lower:] Lowercase letters.
[:upper:] Uppercase letters.

Quantifiers

* matches preceding 0 or more times
.* any number of any characters
? matches preceding 0 or none
+ matches preceding 1 or more times
{} specify exact number with upper and lower bound

# match all integers that are between 3 to 9 digits
grep -E '[[:digit:]]{3,9} sample.txt

# basic regular expression
grep 'c\?at' sample.txt

# extended regular expression
grep -E 'c?at' sample.txt

Alternation (OR)

grep 'fatal\|error\|critical' /var/log/nginx/error.log 

grep -E 'fatal|error|critical' /var/log/nginx/error.log

Grouping patterns together

# matches careless and less
grep -E '(care)?less' sample.txt

Backslash Expression

Expression Description
\b Match a word boundary.
\< Match an empty string at the beginning of a word.
\> Match an empty string at the end of a word.
\w Match a word.
\s Match a space.
# matching heard or beard
grep '\b[hb]eard\b' sample.txt

References

https://linuxize.com/post/regular-expressions-in-grep/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment