In Vim you can search/replace text in the following way.
:%s/old/new
What does the %s mean?
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.
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.
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.
%
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.
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]
:%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).
%s stands for the whole document. See here:
http://vim.wikia.com/wiki/Ranges
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With