ZisIsNotZis
ZisIsNotZis

Reputation: 1740

vi replaces with empty when searching

In vi (from cygwin), when I do searching:

:%s/something

It just replaces the something with empty string like

:%s/something//  .

I've googled for a while but nothing really mentions this. Is there anything I should add to the .vimrc or .exrc to make this work?

Thanks!

Upvotes: 0

Views: 390

Answers (2)

The format of a substitution in vim is as follows:

:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]

In your case you have omitted the string from the substitution command and here what vim documentation stated about it:

If the {string} is omitted the substitute is done as if it's empty. Thus the matched pattern is deleted. The separator after {pattern} can also be left out then. Example: > :%s/TESTING This deletes "TESTING" from all lines, but only one per line.

For compatibility with Vi these two exceptions are allowed: "/{string}/" and "\?{string}?" do the same as "//{string}/r". "\&{string}&" does the same as "//{string}/".

E146

Instead of the '/' which surrounds the pattern and replacement string, you can use any other single-byte character, but not an alphanumeric character, '\', '"' or '|'. This is useful if you want to include a '/' in the search pattern or replacement string. Example: > :s+/+//+

In other words :%s/something and :%s;something or :%s,something have all the same behavior because the / ; and , in the last examples are considered only as SIMPLE SEPARATOR

Upvotes: 2

SibiCoder
SibiCoder

Reputation: 1496

In vi and vim, when you search for a pattern, you can search it again by simply typing /. It is understood that the previous pattern has to be used when no pattern is specified for searching. (Though, you can press n for finding next occurence)

Same way, when you give a source (pattern) and leave the replacement in substitute command, it assumes that the replacement is empty and hence the given pattern is replaced with no characters (in other words, the pattern is removed)

In your case, you should understand that % stand for whole file(buffer) and s for substitute. To search, you can simply use /, followed by a pattern. To substitute , you will use :s. You need not confuse searching and substituting. Hence, no need for such settings in ~/.exrc. Also, remember that / is enough to search the whole buffer and % isnt necessary with /. / searches the entire buffer implicitly.

You may also want to look at :g/Pattern/. Learn more about it by searching :help global or :help :g in command line.

Upvotes: 2

Related Questions