I am modifying a script that reads in a user email. It is very simple, too simple.
echo -n "Please enter your example.com email address: "
read email
email=${email%%@example.com} # removes trailing @example.com from email
echo "email is $email"
This works, but only for lower case开发者_运维百科 @example.com. How could I modify this to remove the trailing @example.com, case insensitive?
If you have bash 4:
email=${email,,}
email=${email%%@example.com}
Otherwise, perhaps just use tr:
email=$(echo "${email}" | tr "A-Z" "a-z")
email=${email%%@example.com}
Update:
If you are just wanting to strip the host (any host) then perhaps this is really what you want:
email=${email%%@*}
For Bash 3.2 and greater:
shopt -s nocasematch
email='JoHnDoE@eXaMpLe.CoM'
pattern='^(.*)@example.com$'
[[ $email =~ $pattern ]]
email=${BASH_REMATCH[1]} # result: JoHnDoE
How about using sed?
email="$(sed 's|@example\.com$||i' <<<"$email")"
Note the 'i' flag in the sed substitution command which requests case-insensitive matching.
Here's yet another (though a bit lengthy) take on it:
email='JoHnDoE@eXaMpLe.CoM'
email=${email%%@[Ee][Xx][Aa][Mm][Pp][Ll][Ee].[Cc][Oo][Mm]}
echo "email is $email"
echo -n "Please enter your example.com email address: "
read _email
_email=$(echo $_email | awk 'BEGIN{ FS="@" } {print $1}')
echo $_email
and for transfer email to lower case you can use declare, such as
declare -l email=$email
Use case insensitive matching to a regular expression:
echo -n "Please enter your example.com email address: "
read email
shopt -s nocasematch # Makes comparisons case insensitive
if [[ $email =~ example.com$ ]]; then
domain=${BASH_REMATCH[0]}
echo "email is ${email%%@$domain}"
fi
Alternatively, you can cut off a string based on its length (which only makes sense if you know that the user entered the domain correctly):
echo -n "Please enter your example.com email address: "
read email
domain=example.com
email_length=${#email}
domain_length=${#domain}
name_length=$(($email_length-$domain_length-1))
email=${email:0:$name_length} # removes trailing @example.com from email
echo "email is $email"
精彩评论