11

Possible Duplicate:
Case preserving substitute in Vim

Is it possible to do a search and replace in vim that preserves the case of the search term? This was a useful feature in intelliJ that I miss.

For instance, something like:

:s/[uU]ser/[pP]erson/ (obviously, this doesn't work)

Such that:

user->person
User->Person

Another example with multiple characters to preserve:

:s/[mM]y[uU]ser/[tT]his[pP]erson/g

Such that:

myuser->thisperson
myUser->thisPerson
MyUser->ThisPerson
Community
  • 1
  • 1
case nelson
  • 3,537
  • 3
  • 30
  • 37

3 Answers3

8

There are a few approaches that can be taken. If you want to stick with basic Vim functionality, you can do something like

:%s/[uU]ser/\=submatch(0) ==# 'user' ? 'person' : 'Person'/g

If you have Vim built with Perl bindings, you can make use of :perldo. Depending on the length of the matching/replacing words and where the case you want to preserve is, this may or may not work.

:perldo s/(user)/"\L$1" ^ $1 ^ 'person'/ieg

Or you can make use of one of the various scripts that implement such functionality.

jamessan
  • 41,569
  • 8
  • 85
  • 85
  • SmartCase looks like what I want – case nelson Dec 16 '09 at 17:51
  • This answer has helped me doubly. I used keepcase for case-preserving searches. I came back to your answer to figure out how to do search and replace with varied pluralization spellings (group/groups => body/bodies). – Eric Hu Jan 27 '12 at 22:32
2

Redone the answer after giving it some thought ;-)

:s@\([Uu]\)ser@\=((submatch(1)=="U")?"P":"p")."erson"@gc

Of course it can be improved, but the idea stays.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
2

There's a plugin for vim: keepcase.vim

tangens
  • 39,095
  • 19
  • 120
  • 139
  • This is close, but I've updated the question with another example with CamelCase replacement that this plugin doesn't seem to be able to handle, unless I'm mistaken. The first example works like :SubstituteCase#\cuser#person#g – case nelson Dec 16 '09 at 17:49