Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract email string from string in bash

Tags:

string

bash

I have a variable: $change.

I have tried to extract email from it (find the string between "by" and "@"):

change="Change 1234 on 2016/08/31 by [email protected] 'cdex abcd'"
email=$(echo $change|sed -e 's/\by\(.*\)@/\1/')

It did not work.

like image 829
OkyDokyman Avatar asked Feb 28 '26 23:02

OkyDokyman


1 Answers

You have an escape character before b, which makes it \b. And this is a word boundary, so something you don't want here.

See the difference:

$ echo "$change" | sed -e 's/\by\(.*\)@/\1/'
#                            ^
Change 1234 on 2016/08/31 by [email protected] 'cdex abcd'
$ echo "$change" | sed -e 's/by\(.*\)@/\1/'
#                            ^
Change 1234 on 2016/08/31  namecompany.com 'cdex abcd'
#                        ^
#                        by is not here any more

But if you want to get the name, just use .* to match everything up to by:

$ echo "$change" | sed -e 's/.*by\(.*\)@/\1/'
 namecompany.com 'cdex abcd'

Finally, if what you want is just the data between by (note the trailing space) and @, use either of these (with -r you don't have to escape the captured groups):

sed -e 's/.*by \(.*\)@.*/\1/'
sed -r 's/.*by (.*)@.*/\1/'

With your input:

$ sed -e 's/.*by \(.*\)@.*/\1/' <<< "Change 1234 on 2016/08/31 by [email protected] 'cdex abcd'"
name
like image 169
fedorqui 'SO stop harming' Avatar answered Mar 03 '26 11:03

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!