Unix & Linux
vim regular-expression
Updated Thu, 04 Aug 2022 21:11:50 GMT

vim find and replace around a string


In VIM, if, for example, I have the text

http://a.com
http://b.com

is it possible to find all lines (the whole line) and replace it with something before and after it, such as:

<a href="http://a.com">http://a.com</a>
<a href="http://b.com">http://b.com</a>

Note that the text from every line is repeated. Once for the href and another for the text.




Solution

:%s:.*:<a href="&">&</a>:

Same as in ed/sed/perl...

Another less ex and more vim-like way would be: if you know how to do it once for a line, record it as a macro and then run :%normal @m where m is that macro.

Like (in normal mode): qmS<a href="<Ctrl-R>""><Ctrl-R>"</a><Esc>q to record the macro.





Comments (2)

  • +0 – Didn't work for me. It gave me this error:E748: No previously used register Press ENTER or type command to continue — Feb 03, 2016 at 22:28  
  • +0 – @AlexandreSantos, oops. I had overlooked that | was special. Should work better with : — Feb 04, 2016 at 04:58