I want to extract username from email. Example: johndoe@gmail.com 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="johndoe@gmail.com"
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!
Instead of worrying about the position, remove everything from the @
onward.
$ str="johndoe@gmail.com"
$ 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).