Replace source word with containing /(forward slash) to destination word in VI editor command window
Sophia Terry
I'm facing problem while cmake compilation wherein, there are thousands of /root/repo/ are there & I want to replace with /repo/ . Because of / in the source word the command
:%s/srcWrd/dstwrd/gc is not working. Kindly guide here about how to proceed.
sample input : A line in the file contains
/root/repo/my-gerrit/myData.cppIt should look like
/repo/my-gerrit/myData.cppI've tried below command inside file, but it doesn't work as expected.
:%s\/root\/\repo\/repo/gc 8 2 Answers
In the example you gave, with a file containing
/root/repo/my-gerrit/myData.cppThis can be changed to
/repo/my-gerrit/myData.cppwith the command :%s/\root//gc.
You attempted %s\/root\/\repo\/repo/gc, which lacks the normal forward slashes. To replace /root/repo/ with /repo/, the command would be %s/\/root\/repo\//\/repo\//gc
Note that forward slashes that you want to replace are escaped with \. Forward slashes that is part of the command is not escaped.
While escaping the forward slashes with backslashes is an option, it's much easier to use a different separator altogether.
Such as:
:%s#/root/repo/#/repo/#gcOr:
:%s+/root/repo/+/repo/+gcOr:
:%s,/root/repo/,/repo/,gcYou can use almost any symbol as a separator on the :s command, so it should be easy to find one that doesn't require escaping that symbol in the pattern or replacement.
See also :help E146