Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all instances of character between tags with vim

Tags:

regex

replace

vim

I need to replace all instances of / character with \ between < filename >...< / filename > tags.

The file has like 2.000 of those tags and I only need to replace the / character inside those tags.

How can i do?

like image 689
Oletros Avatar asked Nov 01 '11 18:11

Oletros


1 Answers

Edit: Given the new information, the below substitution would probably work:

:%s/<filename>\zs.\{-}\ze<\/filename>/\=substitute(submatch(0), '\/', '\', 'g')/ 

Explaination:

  • %s: substitute across the entire file
  • /<filename>: start of pattern and static text to match against
  • \zs: start of the matched text
  • .\{-}: any character, non greedy
  • \ze: end of matched text
  • <\/filename>/: end of targeted tag and pattern
  • \=: evaluate the replacement as a vim expression
  • substitute(submatch(0), '\/', '\', 'g')/: replace all /'s with \ in the matched text.

Original answer:

I'm going to assume you mean XML-style tags here. What I would do is visually select the area you'd like to operate on, then use the \%V regex atom to only operate on that selection.

vit:s!\%V/!\\!g

Should do the trick. Note that when pressing :, vim will automatically add a range for the visual selection, the actual substitution command will look like:

:'<,'>s!\%V/!\\!g
like image 89
Randy Morris Avatar answered Oct 21 '22 12:10

Randy Morris