user3543078
user3543078

Reputation: 85

Bash string manipulation based on token

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

Answers (3)

anana
anana

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

jaypal singh
jaypal singh

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

that other guy
that other guy

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

Related Questions