I need to extract email address from a string like this (I'm making a log parser): <some text> from=, <some text>

with egrep (or grep -Eo). So the string needs to be pulled out only between "from=" and "," , because the other parts of log contain email addresses too, like to= and etc

1

3 Answers

Using grep -oP:

s='<some text> from=, <some text>' grep -oP '(?<=from=).*?(?=,)' <<< "$s" 

OR else avoid lookbehind by using \K:

grep -oP 'from=\K.*?(?=,)' <<< "$s" 

In case your grep doesn't support -P (PCRE) use this sed:

sed 's/.*from=\(.*\),.*/\1/' <<< "$s" 
4

Try awk

echo '<text> from=, <text>' | awk -F[=,] '{print $2}' 

Here $2 can be a different number based on its position.

Sample for word between symbols "(", ")":

echo "Linux Foundation Certified Engineer (LFCE-JP)" | awk -F[\(\)] '{print $2}' LFCE-JP 
3

A purely bash solution, requires two steps to strip prefix & suffix separately (but probably runs faster, because no subprocesses):

#!/bin/bash orig='from=, <some text>' one=${orig#*from=} two=${one%,*} printf "Result:\n" printf "$orig\n" printf "$one\n" printf "$two\n" 

Output:

Result: from=, <some text> , <some text> 

Notes:

  • ${var#*pattern} using # strips from the start of $var up to pattern
  • ${var%pattern*} using % strips from end of $var, up to pattern
  • similar could be accomplished with ${var/pattern/replace} (and leaving replace blank), but it's trickier since full regexp isn't supported (ie, can't use ^ or '$'), so you can't do (for example) /^from=//, but you could do in step one ${var/*from=/} and then in step two, do ${var/,*/} (depending on your data, of course).
  • see also:
1