![](/img/trans.png)
[英]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.