You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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