10

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?

3 Answers 3

16

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.

3
  • Thanks. Exactly what I wanted. didn't get this on my google search, dunno why.
    – MohitC
    Commented Jan 8, 2016 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. Commented Jan 8, 2016 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. Commented Jan 8, 2016 at 22:58
7

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.

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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