簡體   English   中英

如何使用Vim或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>

分解:

  1. :g[lobal]作用於與模式匹配的每一行,請參閱:h :global

  2. h2我們正在尋找的模式,它可能會變得更聰明一些。

  3. norm[al]運行正常模式命令,請參閱:h :normal

  4. O在當前行上方打開一個新行並進入插入模式。

  5. <hr />是您要插入的內容。

  6. 我們點擊<CR><RETURN> )來運行整個事情。

另一種方法,使用單一替換:

:%s/^\s*<h2/<hr \/>\r&<CR>

分解:

  1. :%s[ubstitute]/在緩沖區的每一行上執行替換,請參閱:h :s

  2. ^將模式錨定到行的開頭。

  3. \\s*匹配任何數字(0到多個)空格字符。 如果您確定所有HTML標記都在第1列,則不是嚴格要求的。

  4. <h2是我們真正尋找的模式。

  5. <hr />是我們想要插入的內容。

  6. 因為我們希望它在自己的行上,所以后面跟着一個\\r

  7. 最后,匹配的文本&

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

命令行標志的說明:

  • -i就地編輯(替換現有文件),備份到your_file.html~
  • -p打印文件中的每一行
  • -e為文件中的每一行執行的代碼

如果該行包含( /<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM