Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Replace source word with containing /(forward slash) to destination word in VI editor command window

Writer 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.cpp

It should look like

/repo/my-gerrit/myData.cpp

I'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.cpp

This can be changed to

/repo/my-gerrit/myData.cpp

with 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.

2

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/#gc

Or:

:%s+/root/repo/+/repo/+gc

Or:

:%s,/root/repo/,/repo/,gc

You 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy