[英]How to match above and below lines, then insert words in between them by using Perl?
[英]How do I insert a line above specific lines in a file using Vim or Perl?
我想插入这一行
<hr />
在文件中每次出现标题2行时 - 例如,在该模式之上
<h2>variable pattern here</h2>
所以上面应该成为
<hr />
<h2>variable pattern here</h2>
我怎么能用Vim,Sed或Perl做到这一点?
vim方式:
cmd :g/<h2>/normal O<hr />
将完成这项工作。
在这里看到:(我从sudo_O拿了例子)
使用sed
你可以做sed '/<h2>/i <hr />'
:
$ cat file
<html>
<h2>variable pattern here</h2>
<h3>not here</h3>
<h2>heading</h2>
<h2>Something</h2>
$ sed '/<h2>/i <hr />' file
<html>
<hr />
<h2>variable pattern here</h2>
<h3>not here</h3>
<hr />
<h2>heading</h2>
<hr />
<h2>Something</h2>
第一部分/<h2>/
匹配包含<h2>
,第二部分使用i
命令在匹配的行上方插入<hr />
。
sed
一个不错的选择是-i
这将更改保存回文件而不是打印到stdout
但要确保更改是正确的。
sed -i '/<h2>/i <hr />' file
在Vim中做到这一点的众多方法之一:
:g/h2/norm O<hr /><CR>
分解:
:g[lobal]
作用于与模式匹配的每一行,请参阅:h :global
。
h2
我们正在寻找的模式,它可能会变得更聪明一些。
norm[al]
运行正常模式命令,请参阅:h :normal
。
O
在当前行上方打开一个新行并进入插入模式。
<hr />
是您要插入的内容。
我们点击<CR>
( <RETURN>
)来运行整个事情。
另一种方法,使用单一替换:
:%s/^\s*<h2/<hr \/>\r&<CR>
分解:
:%s[ubstitute]/
在缓冲区的每一行上执行替换,请参阅:h :s
。
^
将模式锚定到行的开头。
\\s*
匹配任何数字(0到多个)空格字符。 如果您确定所有HTML标记都在第1列,则不是严格要求的。
<h2
是我们真正寻找的模式。
<hr />
是我们想要插入的内容。
因为我们希望它在自己的行上,所以后面跟着一个\\r
,
最后,匹配的文本&
。
use strict;
use warnings;
use Tie::File;
tie my @file, 'example.html'
or die "Unable to tie file: $!";
@file = map { m!<h2>.*</h2>!
? ( "<hr />", $_ )
: $_ } @file;
untie @file;
Perl中的命令行解决方案。
perl -i~ -p -e'/<h2>/ and $_ = "<hr />\n$_"' your_file.html
命令行标志的说明:
如果该行包含( /<h2>/
),则将<hr />
到它(当前行在$ _中)。
但你有没有考虑过这是最好的方法? 如果你想在每个H2元素上面添加一行,那么也许你应该用CSS做到这一点?
perl -plne 'print "<hr />" if(/\<h2\>variable pattern here\<\/h2\>/)' your_file
输入文件:
> cat temp
<h2>variable pattern here</h2>
1
<h2>variable pattern here</h2>
2
<h2>variable pattern here</h2>
3
4
<h2>variable pattern here</h2>
现在执行
> perl -plne 'print "<hr />" if(/\<h2\>variable pattern here\<\/h2\>/)' temp
<hr />
<h2>variable pattern here</h2>
1
<hr />
<h2>variable pattern here</h2>
2
<hr />
<h2>variable pattern here</h2>
3
4
<hr />
<h2>variable pattern here</h2>
这将只输出到控制台。 如果要在适当的位置更改它:
perl -pi -lne 'print "<hr />" if(/\<h2\>variable pattern here\<\/h2\>/)' your_file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.