3

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 user@example.com 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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3543078
  • 75
  • 1
  • 4
  • possible duplicate of [How do I split a string on a delimiter in bash?](http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash) – BMW Apr 17 '14 at 04:36

3 Answers3

4

Use parameter expansion:

email="foo.bar@example.com"
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.

that other guy
  • 116,971
  • 11
  • 170
  • 194
2

You can use bash string substitution (considering the fact that it is an email address and cannot have two@ signs)

$ var=user@example.com
$ echo "${var/@*/}"
user
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
1

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
anana
  • 1,461
  • 10
  • 11
  • 1
    Or use a here-string `cut -d@ -f1 <<< "$ADDRESS"`. The parameter expansion answers will be faster than spawning a `cut` process though. – Digital Trauma Apr 16 '14 at 22:25