Reputation: 85
I tried searching for this and couldn't quite find what I was looking for.
I have a variable in Bash/Shell that contains an email address. I would like to extract everything that comes before the "@" sign and put that into a new variable.
So [email protected]
should be just user
.
All the string manipulation looks for a length and position. The position should always be 0, but I really need to find that "@" token.
Upvotes: 3
Views: 252
Reputation: 1501
You can easily do this with cut
, that splits a string by a delimiter character and extracts one of the resulted substrings (or "fields"):
echo $ADDRESS | cut -d@ -f1
# ^ ^
# delimiter extract first field
Upvotes: 1
Reputation: 77135
You can use bash
string substitution (considering the fact that it is an email address and cannot have two@
signs)
$ [email protected]
$ echo "${var/@*/}"
user
Upvotes: 2
Reputation: 123550
Use parameter expansion:
email="[email protected]"
user=${email%%@*}
echo "$user"
${email%%@*}
consists of ${..}
(parameter expansion) with the parts email
, the variable; %%
, the operator to delete the longest match from the end of the string; and @*
, a glob pattern matching @ followed by anything.
Upvotes: 4