Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there any alternative in vim search and replace for strings, than having to escape every special character in string.

For example, If I want to match following string and replace with something

[ERROR] Login unsucessful

Then I have to do

:%s/\[ERROR\]\ Login\ unsucessful/something/g

And it becomes lot more uglier and painful for complex strings containing lot of special characters

I would like to do something like

:%s/"[ERROR] Login unsucessful"/something/g

which would avoid all escaping. Is there any feature like this?

share|improve this question
up vote 15 down vote accepted

You can use the very-nomagic switch. See :h \V for details. This would give you %s/\V[ERROR] Login unsuccessful/something/g. There is also the nomagic switch \M, which is a lighter version of \V and does not seem to be widely used.

Also note that you don't have to escape spaces as you do in your example, even when not using \V.

share|improve this answer
    
Thanks. Exactly what I wanted. didn't get this on my google search, dunno why. – MohitC Jan 8 at 12:47
2  
@MohitC I map / to /\v to enable "very magic" for most searches, so I have mapped // to / to start an unmodified search (useful for going through search history ignoring modifiers) and /v/ to /\V to quickly turn off all magic for searching. – Kyle Strand Jan 8 at 22:56
    
@MohitC In fact, my setup is more complicated than that, because I also use a plugin to use "very magic" as consistently as possible in all contexts. See my answer here. – Kyle Strand Jan 8 at 22:58

You don't need to escape spaces. So this:

:%s/\[ERROR\]\ Login\ unsucessful/something/g

should actually be:

:%s/\[ERROR\] Login unsucessful/something/g

And, of course, you can enable very nomagic "mode" to make those special characters less special:

:%s/\V[ERROR] Login unsucessful/something/g

See :help /magic.

share|improve this answer

In addition to the nomagic flags mention in other answers.

It is often the case that you don't need to be precise in your search string

For example, to match

[ERROR] Login unsucessful

You could use the expression

.ERROR. Login unsucessful

Obviously, you have to know that your data won't contain other strings, differing from your intended target but matching the expression.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.