首页 > 解决方案 > 匹配不包含特定模式的行并在最后附加字符串 - Bash

问题描述

我正在尝试搜索文件并在与特定模式不匹配的每一行的末尾附加一个特定的字符串。

这是文件的一部分:

<h3>Release: </h3>

** Commit to create release 
** Add firmware 

<h4>Application changes: </h4>

** Add testfunction <br/>
** Add update support to application<br/>

我想<br/>在它丢失的每一行的末尾附加(如果它不是标题,那么基本上任何不以>结尾的行)。

我尝试匹配所有不以在 Perl中> and empty space after that使用结尾的行:^(?!.*>\s*)

perl -pe 's/^(?!.*>\s*)/$&<br\/>/' temp.html > output.html

它可以找到该行,但不幸的是它附加到该行的开头,即使我在匹配的行之后附加:$&<br\/>。我想<br/>在最后追加。

我的代码输出:

<h3>Release: </h3>

<br/>** Commit to create release 
<br/>** Add firmware 

<h4>Application changes: </h4>

** Add testfunction <br/>
** Add update support to application<br/>

我想要的输出:

<h3>Release: </h3>

** Commit to create release <br/>
** Add firmware <br/>

<h4>Application changes: </h4>

** Add testfunction <br/>
** Add update support to application<br/>

谁能告诉我我做错了什么?

标签: bashperl

解决方案


我认为你的意思是这样的,使用否定的后向断言:

perl -pe 's/(?<!\>)$/<br\/>/' temp.html > output.html

请注意,我删除了\s*- 这是因为 Perl 正则表达式引擎不支持可变长度的后视。我还注意到这在我的系统上存在空行问题。

用一些简单的东西if代替使用怎么样?

perl -pe 's/$/<br\/>/ if !/\>\s*$/ && !/^\s*$/' temp.html > output.html

推荐阅读