首页 > 解决方案 > 提取匹配文本之前的所有文本,直到另一个匹配

问题描述

我正在尝试使用正则表达式从“multipath -l”命令输出中提取文本,以获取匹配的磁盘设备名称(例如“sdaf”)之间的所有文本(包括匹配文本的行)并向后匹配以 mpath 开头的下一行(在本例 mpathf)。行数不同,所以我不能使用“grep -B”。

所以从这个例子

mpatha (360060160e6e04400e819a6ac680fe811) dm-7 DGC,VRAID
size=50G features='1 queue_if_no_path' hwhandler='1 emc' wp=rw
|-+- policy='round-robin 0' prio=0 status=active
| |- 0:0:6:0  sdw  65:96  active undef running
| `- 0:0:5:0  sdt  65:48  active undef running
`-+- policy='round-robin 0' prio=0 status=enabled
  |- 0:0:4:0  sdq  65:0   active undef running
  `- 0:0:7:0  sdz  65:144 active undef running
mpathf (36006016016003f00cf52bfe07b10e811) dm-2 DGC,VRAID
size=50G features='1 queue_if_no_path' hwhandler='1 emc' wp=rw
|-+- policy='round-robin 0' prio=0 status=active
| |- 0:0:1:20 sdh  8:112  active undef running
| |- 2:0:9:20 sdan 66:112 active undef running
| |- 0:0:2:20 sdl  8:176  active undef running
| `- 2:0:6:20 sdav 66:240 active undef running
`-+- policy='round-robin 0' prio=0 status=enabled
  |- 0:0:0:20 sdd  8:48   active undef running
  |- 2:0:8:20 sdaj 66:48  active undef running
  |- 0:0:3:20 sdp  8:240  active undef running
  |- 2:0:7:20 sdar 66:176 active undef running
  `- 2:0:5:20 sdaf 65:240 active undef running

我想获取文本

mpathf (36006016016003f00cf52bfe07b10e811) dm-2 DGC,VRAID
size=50G features='1 queue_if_no_path' hwhandler='1 emc' wp=rw
|-+- policy='round-robin 0' prio=0 status=active
| |- 0:0:1:20 sdh  8:112  active undef running
| |- 2:0:9:20 sdan 66:112 active undef running
| |- 0:0:2:20 sdl  8:176  active undef running
| `- 2:0:6:20 sdav 66:240 active undef running
`-+- policy='round-robin 0' prio=0 status=enabled
  |- 0:0:0:20 sdd  8:48   active undef running
  |- 2:0:8:20 sdaj 66:48  active undef running
  |- 0:0:3:20 sdp  8:240  active undef running
  |- 2:0:7:20 sdar 66:176 active undef running
  `- 2:0:5:20 sdaf 65:240 active undef running

提前致谢

标签: regexbashtextawksed

解决方案


我可以通过将行存储在变量中来实现。我重置它或在需要时打印它。

多路径.awk:

        {output = output "\n" $0}   /* store line in variable */
/^mpath/ {output = $0}              /* reset buffer */
/sdaf/   {print output}             /* print buffer */

我使用与您的示例相对应的文件得到您的结果multipath.txt(我尚未安装多路径工具)。我启动它:

awk -f multipath.awk multipath.txt

您可以在一行中编写 awk 命令:

 multipath -l | awk    '{output = output "\n" $0}   /^mpath/ {output = $0}   /sdaf/   {print output}' 

推荐阅读