匹配两条线,替换为三条线

时间:2016-02-25 03:01:46

标签: linux unix sed

我需要使用sed将每个匹配的两行模式替换为三行模式。这是我的输入文件(tempfile.txt)。

lease 192.168.6.100 {
  binding state free;
  hardware ethernet 00:e0:4c:68:00:96;
}
lease 192.168.6.100 {
  binding state active;
  hardware ethernet 00:e0:4c:68:00:96;
  client-hostname "andrew-H81M-S2PH";
}
lease 192.168.6.100 {
  binding state free;
  hardware ethernet 00:e0:4c:68:00:96;
}
lease 192.168.6.100 {
  binding state active;
  hardware ethernet 00:e0:4c:68:00:96;
  client-hostname "andrew-H81M-S2PH";
}

基本上,如果是client-hostname "HOSTNAME";  如果缺少,则应使用tab替换为newline

我的尝试: sed 'N; /hardware.*}/d; P; D' tempfile.txt

结果是:

lease 192.168.6.100 {
  binding state free;
lease 192.168.6.100 {
  binding state active;
  hardware ethernet 00:e0:4c:68:00:96;
  client-hostname "andrew-H81M-S2PH";
}
lease 192.168.6.100 {
  binding state free;
lease 192.168.6.100 {
  binding state active;
  hardware ethernet 00:e0:4c:68:00:96;
  client-hostname "andrew-H81M-S2PH";
}

这是我想要的输出。

lease 192.168.6.100 {
  binding state free;
  hardware ethernet 00:e0:4c:68:00:96;
  <tab>
}
lease 192.168.6.100 {
  binding state active;
  hardware ethernet 00:e0:4c:68:00:96;
  client-hostname "andrew-H81M-S2PH";
}
lease 192.168.6.100 {
  binding state free;
  hardware ethernet 00:e0:4c:68:00:96;
  <tab>
}
lease 192.168.6.100 {
  binding state active;
  hardware ethernet 00:e0:4c:68:00:96;
  client-hostname "andrew-H81M-S2PH";
}

正如您所看到的,在曲线之间始终存在三条线。这就是我的目标。

2 个答案:

答案 0 :(得分:2)

这样可以解决问题(管道cat -A显示不可打印的字符):

$ sed -r 'N;s/^([[:space:]]*hardware.*)(\n})$/\1\n\t\2/;t;P;D' infile | cat -A
lease 192.168.6.100 {$
  binding state free;$
  hardware ethernet 00:e0:4c:68:00:96;$
^I$
}$
lease 192.168.6.100 {$
  binding state active;$
  hardware ethernet 00:e0:4c:68:00:96;$
  client-hostname "andrew-H81M-S2PH";$
}$
lease 192.168.6.100 {$
  binding state free;$
  hardware ethernet 00:e0:4c:68:00:96;$
^I$
}$
lease 192.168.6.100 {$
  binding state active;$
  hardware ethernet 00:e0:4c:68:00:96;$
  client-hostname "andrew-H81M-S2PH";$
}$

这不是删除匹配,而是捕获应该围绕空行的两行,并替换之间的换行符和制表符。我还添加了一些锚点以便更安全地匹配。

涉及一些技巧,因为模式空间在替换后包含两个换行符,但P;D仅打印第一行并开始一个新的循环,这也导致在包含{{的行后面出现不需要的换行符1}}。

更详细地解释:

client-hostname

答案 1 :(得分:1)

我冒昧地添加另一个卷曲......

../branches/my-branch