String:
name@gmail.com
Checking for:
@
.com
My code
if [[ $word =~ \"@\" ]]
then
if [[
You can use a very very basic regex:
[[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]]
It looks for a string being exactly like this:
at least one a-z char
@
at least one a-z char
.
at least one a-z char
It can get as complicated as you want, see for example Email check regular expression with bash script.
$ var="a@b.com"
$ [[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]] && echo "kind of valid email"
kind of valid email
$ var="a@.com"
$ [[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]] && echo "kind of valid email"
$
why not go for other tools like perl:
> echo "x@gmail.com" | perl -lne 'print $1 if(/@(.*?)\.com/)'
gmail
The glob pattern would be: [[ $word == ?*@?*.@(com|ca) ]]
?
matches any single character and *
matches zero or more characters
@(p1|p2|p3|...)
is an extended globbing pattern that matches one of the given patterns. This requires:
shopt -s extglob
testing:
$ for word in @.com @a.ca a@.com a@b.ca a@b.org; do
echo -ne "$word\t"
[[ $word == ?*@?*.@(com|ca) ]] && echo matches || echo does not match
done
@.com does not match
@a.ca does not match
a@.com does not match
a@b.ca matches
a@b.org does not match