Remove domain from email using linux substring bash

1.9k Views Asked by At

I want to extract username from email. Example: [email protected] The domain will always be @gmail.com, but the length of username can be different But I must use substring in linux bash (no grep, sed, cut, and others) like:

str="[email protected]"
echo ${str:position:length}

OR maybe using loop like:

length=`expr length "$str"`
for ((i=0; i<$length; i++))
do
    echo ${str:$i:length}
done

The problem is, what should i write in the position and length. How do the code know if I it needs to extract all letters before '@'. Any idea? Thanks!

1

There are 1 best solutions below

5
On BEST ANSWER

Instead of worrying about the position, remove everything from the @ onward.

$ str="[email protected]"
$ echo "${str%@*}"
johndoe

Sidenote: Normally it's best to use printf '%s\n' to safely print unknown data, but I'm assuming these are valid Gmail usernames, which are already safe, so echo is fine. The format is something like [a-z0-9][a-z0-9.]{4,28}[a-z0-9] (regex).