Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting, how to remove trailing substring, case insensitive?

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?

like image 222
basher1 Avatar asked Dec 01 '10 22:12

basher1


People also ask

How do I strip a string in Bash?

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.

How do I remove the last letter in Bash?

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}

How do I remove a prefix in Bash?

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.


2 Answers

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%%@*}
like image 56
kanaka Avatar answered Sep 21 '22 23:09

kanaka


For Bash 3.2 and greater:

shopt -s nocasematch
email='[email protected]'
pattern='^(.*)@example.com$'
[[ $email =~ $pattern ]]
email=${BASH_REMATCH[1]}    # result: JoHnDoE
like image 34
Dennis Williamson Avatar answered Sep 24 '22 23:09

Dennis Williamson