geotheory
geotheory

Reputation: 23690

Regex replace more than one string in Vim

I have documents with groups of <hr/> tags:

<p>stuff</p>
<hr/>
<hr/>
<hr/>
<p>stuff</p>

Grateful for tip how to replace with a single instance of this tag in Vim.

Upvotes: 0

Views: 81

Answers (3)

Alan G&#243;mez
Alan G&#243;mez

Reputation: 378

Also works:

:%s/\(<hr\/>\n\)\+/<hr\/>\r

Upvotes: 0

sidyll
sidyll

Reputation: 59327

You can make <hr/>\n a group and search for multiples of it, replacing with a single one. Also note that in Vim you can use different delimiters, which is specially helpful if you're working with slashes for example. And you don't need to close the substitute command if you don't have flags.

:%s#\(<hr/>\n\)\+#\1

With \v to enable very magic, even more escaping is avoided. However the < and > will be treated as special word boundaries. So you have to escape them instead.

:%s#\v(\<hr/\>\n)+#\1

And of course, if the only duplicated lines in your file are those tags, this is enough as well:

:%!uniq

Upvotes: 3

anubhava
anubhava

Reputation: 786291

You can use this search-replace in vim:

:%s/<hr\/>\n\(<hr\/>\n\)\+/\1/

<hr\/>\n\(<hr\/>\n\)\+ will find 2 or more lines containing <hr/> and we replace it using \1 which is <hr/>\n.

Upvotes: 1

Related Questions