Replace all instances of characters between tags with vim

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

The file has about 2,000 of these tags, and I only need to replace the / character inside these tags.

How can i do this?

+7
source share
3 answers

Edit: with the new information, the following substitution is likely to work:

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

Explaination:

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

Original answer:

I'm going to suggest that you mean XML style tags. What I would do is visually select the area in which you want to work, and then use the regex atom \%V to work only with that choice.

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

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

 :'<,'>s!\%V/!\\!g 
+9
source

Iff, we can assume that the tags are on the same line, it's simple:

Note Enter ^M as Cv Cm ( Cq Cm on Windows)

 :g/<filename>/norm! /filename>/e^Mvity:let @"=substitute(@", '/', '\\', "g")^Mgvp 

Hmmm, integrating Randy’s hint on using \% V in the template makes it easy:

 :g/<filename>/norm! /filename>/e^Mvit:s#\%V/#\\#g^M 

I tested both. Wow. I will explain now. Hold on

  • :g/<filename>/ - _ for each line containing <filename>
  • norm! - _execute regular commands (ignoring mappings)
  • /filename/e Enter go to the end of the open tag
  • vit - select the inner text of this tag in visual mode
  • :s#\%V/#\\#g Enter - _ in this visual selection, replace (replace \ with / )
+2
source

VIM has a sharp learning curve, like a regular expression. I believe this team will do this. You must avoid each char with '\'.

 :%s/\//\\/g 
0
source

All Articles