krystah
krystah

Reputation: 3733

Vim Ex mode regex: How to do case-aware word swap

A regular obstacle I meet is wanting to replace all occurrences a word with its replacement, but also its alternate-cased variants. I want to do this in a single command. Example:

Original:
Bananas? Ew, I don't like bananas.

Nifty regex:
:%s/Something/Clever/g

Result:
Grapes? Ew, I don't like grapes.

Is there any way to perform this replacement in a neat way that's faster than doing both the following commands?
:%s/Bananas/Grapes/g
:%s/bananas/grapes/g

Upvotes: 1

Views: 66

Answers (3)

Mariano Macchi
Mariano Macchi

Reputation: 242

If ignorecase is set:

:s/bananas/Grapres/|s//grapes

But this is more a trick (// stands for the previous searched pattern, i.e. bananas) than a solution, I'd rather use a plugin as others suggested.

Upvotes: 0

Luc Hermitte
Luc Hermitte

Reputation: 32926

You also have :SubstituteCase from keepcase.vim

:SubstituteCase#\ctoto\(Titi\)tata#\1Tutu#g

     totoTitiTata -> titiTutu
     TotoTitiTata -> TitiTutu
     tototititata -> tititutu
     tototitiTata -> titiTutu
     TototitiTata -> TitiTutu 

Upvotes: 1

Ingo Karkat
Ingo Karkat

Reputation: 172540

There are several plugins that allow this:

:%s/bananas/\=SmartCase("grapes")/ig
:%SmartCase/bananas/grapes/g
:%Subvert/{b,B}ananas/{g,G}rapes/g

Upvotes: 2

Related Questions