Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim Search/Replace, meaning of %s

Tags:

replace

vim

In Vim you can search/replace text in the following way.

:%s/old/new

What does the %s mean?

like image 399
9er Avatar asked Mar 11 '14 13:03

9er


People also ask

How do I search and replace in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

What does percent do in Vim?

At the beginning of a Vim command line statement, you can specify a range over which to operate. % is a common range for specifying the whole file, shorthand for 1,$ , i.e. line 1 to end of file.

How do you replace special characters in vi?

You can use all the special matching characters for searches in search-and-replace. Then press the Return key. Then and press Return. You can modify this command to halt the search and make vi query whether you want to make the replacement in each instance.


4 Answers

% is the range over which the :s command (short for :substitute) will be run. % itself is short for the range :1,$, which means Line 1 to the last line in the buffer.

The Vim help has a couple topics (user manual - :help 10.3, reference manual - :help cmdline-ranges) describing the forms that ranges can take.

like image 180
jamessan Avatar answered Oct 22 '22 08:10

jamessan


The syntax for :s (which is short for :substitute) is:

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

The % range means "the whole file".

This is very powerful; if you would want to do substitutions on just line 1, you would use:

:1s/a/b/

Or, for just lines 1 to 3:

:1,3s/a/b/

A very useful (related) trick, is to highlight lines with visual mode (V), and then use :s to substitute just on the lines you highlighted.

See: :help [range]

like image 41
Martin Tournoij Avatar answered Oct 22 '22 10:10

Martin Tournoij


:%s/old/new/

This will search the entire document for "old" and replace the first instance on each line with "new". You can use :%s/old/new/g to replace all instances of "old" with "new".

(Updated based answer on jamessan's comment).

like image 2
GrandAdmiral Avatar answered Oct 22 '22 09:10

GrandAdmiral


%s stands for the whole document. See here:

http://vim.wikia.com/wiki/Ranges

like image 1
easyDaMan Avatar answered Oct 22 '22 08:10

easyDaMan