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?
Example-2: Trim string data using `sed` command `sed` command is another option to remove leading and trailing space or character from the string data. The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed 's/^ *//g', to remove the leading white spaces.
Using Pure Bash. Two Bash parameter expansion techniques can help us to remove the last character from a variable: Substring expansion – ${VAR:offset:length} Removing matching suffix pattern – ${VAR%word}
Since we're dealing with known fixed length strings ( prefix and suffix ) we can use a bash substring to obtain the desired result with a single operation. Plan: bash substring syntax: ${string:<start>:<length>} skipping over prefix="hell" means our <start> will be 4.
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='[email protected]'
pattern='^(.*)@example.com$'
[[ $email =~ $pattern ]]
email=${BASH_REMATCH[1]} # result: JoHnDoE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With