Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern to get string between two specific words/characters using grep [duplicate]

Tags:

regex

grep

bash

I need to extract email address from a string like this (I'm making a log parser): <some text> [email protected], <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

like image 720
Shirker Avatar asked Aug 31 '25 04:08

Shirker


2 Answers

Using grep -oP:

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

OR else avoid lookbehind by using \K:

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

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

sed 's/.*from=\(.*\),.*/\1/' <<< "$s"
[email protected]
like image 54
anubhava Avatar answered Sep 02 '25 17:09

anubhava


Try awk

echo '<text> [email protected], <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
like image 28
Shiplu Mokaddim Avatar answered Sep 02 '25 18:09

Shiplu Mokaddim