提取所有匹配文本之前的文本,直到再次匹配

时间:2019-03-27 10:12:13

标签: regex bash text awk sed

我正在尝试使用正则表达式从“ 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

预先感谢

1 个答案:

答案 0 :(得分:0)

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

multipath.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}'