Shell – Email Matching Regex for Grep

command linegrepregular expressionshell

I created a text file and put some email addresses in it. Then I used grep to find them. Indeed it worked:

# pattern="^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-z]{2,}"
# grep -E $pattern regexfile

but only as long I kept the -E option for an extended regular expression. How do I need to change the above regex in order to use grep without -E option?

Best Answer

Be aware that matching email addresses is a LOT harder that what you have. See an excerpt from the Mastering Regular Expressions book

However, to answer your question, for a basic regular expression, your quantifiers need to be one of *, \+ or \{m,n\} (with the backslashes)

pattern='^[a-zA-Z0-9]\+@[a-zA-Z0-9]\+\.[a-z]\{2,\}'
grep "$pattern" regexfile

You need to quote the pattern variable

Related Question