Replacing a Tag Name in VIM
A simple explanation of using VIM regex syntax to replace acronym tags with abbr tags…preserving title attribute.
I needed to quickly replace acronym tags with abbr tag names since I read somewhere that acronym might eventually be deprecated because of its confusion and redundancy in meaning — although I fully realize the debate is still in progress.
In VIM (vi text editor for the command-line) you can use regular expressions for searching and replacing.
Although a bit confusing at first I have found that my regex chops have quickly improved simply by learning how to use them efficiently within my favorite editor — VIM.
First, if you’re not already familiar with command-mode in VI, we need to invoke the “substitute” mode (type :he substitute for documentation).
The line below will do a search and replace of ‘foo’ with ‘bar’ on the current line (g = greedy/global):
:s/foo/bar/g
To change the acronym tag to abbr we need to do the following:
:s:acronym:abbr:g
Note: I changed the regex delimiter from forward-slash to colon to avoid escaping forward-slashes used in closing HTML tags.
The above example is not good enough, as there’s no gaurantee we are acting only on the tags themselves.
:s:\(<[/]\=\)acronym\([ >]\=\):\1abbr\2:g
A simple explanation for the arcane syntax is that capturing parenthesis need to be escape in VIM: (…)
becomes \(…\)
, and thus can be refered to in the replacement token by \1
, \2
, etc.
The \=
forces a 0 or 1 match on any character(s) defined within the brackets []’s — in this case, we want to first match an option /
forward flash to apply to opening as well as closing tags.
The second set of brackets: [ >]
contains a literal space character and a closing carat to signify the end of the opening or closing tag. This will preserve other HTML attributes (ie - “title”) defined on the opening tag.
Finally, after testing it on one line first and seeing positive results, you can apply it to the entire document by invoking the substitution function in VIM with a preceding “%”.
The final regex applied to the entire document becomes:
:%s:\(<[/]\=\)acronym\([ >]\=\):\1abbr\2:g



















