You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让匹配list:前特定邮箱的多行正则在grep中生效?

解决grep匹配特定区域邮箱的问题

示例文本

some:
- 1test@test.nl\\
- test@test.nlk
- test@test.nl
- test@test.nl test
- some@test.nl


list:
- 1test@test.nl
- test@test.nlk
- test@test.nl
- test@test.nl test
- some@test.nl

需求

匹配list:之前第一个列表(some:下)中的特定邮箱test@test.nl。

问题分析

原正则表达式(- test@test.nl\s*\n).*list:在在线工具中可正常匹配,但在精简版Linux的grep中使用-e、-P、-E参数时,要么报错要么无匹配结果。核心原因是:

  • 标准grep默认逐行处理文本,不支持跨多行的.*匹配
  • 精简版环境可能缺少Perl正则(-P)或扩展正则(-E)的完整支持
  • 基础正则不支持\s这类简写字符集

解决方案

方案1:使用grep的-z参数(环境支持时优先用)

-z参数会将整个文本视为单个字符串,结合-P启用Perl正则实现跨多行匹配,同时用非贪婪匹配避免误匹配后面的列表:

grep -zP '(- test@test.nl\s*\n).*?list:' input.txt

方案2:sed截取目标区域后再grep(兼容性最优)

先通过sed提取some:到list:之间的内容,再用grep筛选目标行,完全依赖标准命令,适配精简环境:

sed -n '/some:/,/list:/p' input.txt | grep '- test@test.nl'

方案3:直接用sed完成匹配

如果grep的扩展功能受限,可直接用sed实现匹配逻辑:

sed -n '/some:/,/list:/{/- test@test.nl/p}' input.txt

内容的提问来源于stack exchange,提问作者Sven van den Boogaart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 05:25:17