使用grep在两个特定单词/字符之间获取字符串的模式 [英] Pattern to get string between two specific words/characters using grep

查看:988
本文介绍了使用grep在两个特定单词/字符之间获取字符串的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从这样的字符串中提取电子邮件地址(我正在做一个日志解析器): <some text> from=someuser@somedomain.com, <some text>

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

egrep(或grep -Eo).因此只需要在"from="","之间拉出字符串,因为日志的其他部分也包含电子邮件地址,例如to=etc

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

推荐答案

使用grep -oP:

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

或者使用\K避免lookbehind:

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

如果您的grep不支持-P(PCRE),请使用此sed:

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

sed 's/.*from=\(.*\),.*/\1/' <<< "$s"
someuser@somedomain.com

这篇关于使用grep在两个特定单词/字符之间获取字符串的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆