In (N)Vim, you can perform search and replace operations using the :substitute command. Here are the basic steps and syntax for doing search and replace:
The basic command for search and replace in (N)Vim is:
:s/pattern/replacement/
:sindicates that you want to substitute.patternis the text you want to search for.replacementis the text you want to replace it with.- The trailing
/is used to end the command.
To replace the first occurrence of "foo" with "bar" on the current line, you would use:
:s/foo/bar/
To replace all occurrences of "foo" with "bar" on the current line, add the g (global) flag:
:s/foo/bar/g
To perform a search and replace throughout the entire file, add the % before the s:
:%s/foo/bar/g
If you want to confirm each replacement, add the c (confirm) flag:
:%s/foo/bar/gc
This will prompt you for confirmation before each replacement.
By default, the search is case-sensitive. To make it case-insensitive, you can add the i flag:
:%s/foo/bar/gi
n: Show the number of occurrences that were made.c: Confirm each substitution.g: Replace all occurrences in the line or file.i: Ignore case in the search.
-
Replace first occurrence in the current line:
:s/pattern/replacement/ -
Replace all occurrences in the current line:
:s/pattern/replacement/g -
Replace all occurrences in the entire file:
:%s/pattern/replacement/g -
Confirm each replacement:
:%s/pattern/replacement/gc -
Case-insensitive replacement:
:%s/pattern/replacement/gi
These commands should help you effectively perform search and replace operations in (N)Vim.
Remember to always back up your files before performing bulk replacements, especially when using the g flag!