Replace Source Word with Containing /(Forward Slash) to Destination Word in Vi Editor Command Window

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

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

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest