vim - How to Search & Replace

To search and replace in Vim, you can use the substitute command, which is represented by :s. Here's a step-by-step guide on how to perform search and replace in Vim:

  1. Enter command mode by pressing the Esc key.
  2. Type :s/ followed by the search pattern you want to find. For example, if you want to find the word "foo", you would type :s/foo.
  3. After the search pattern, type / followed by the replacement text. For example, if you want to replace "foo" with "bar", you would type :s/foo/bar.
  4. By default, the substitute command will only replace the first occurrence of the search pattern on each line. If you want to replace all occurrences on each line, add the g flag at the end of the command. For example, :s/foo/bar/g.
  5. If you want to perform a case-insensitive search, add the i flag at the end of the command. For example, :s/foo/bar/gi.
  6. If you want to confirm each substitution before it is made, add the c flag at the end of the command. For example, :s/foo/bar/gci.
  7. Press Enter to execute the command and perform the search and replace.

Here are some additional tips and considerations when using the substitute command in Vim:

  • To repeat the last search and replace command, you can use the & command. Just press & in command mode to repeat the previous substitution.
  • To search and replace within a specific range of lines, you can specify the range before the s command. For example, :1,5s/foo/bar/g will replace all occurrences of "foo" with "bar" in lines 1 to 5.
  • If you want to search and replace in the entire file, you can use the % symbol to represent the entire range. For example, :%s/foo/bar/g will replace all occurrences of "foo" with "bar" in the entire file.
  • To search and replace only whole words, you can use the \< and \> symbols to mark the beginning and end of the word. For example, :%s/\<foo\>/bar/g will replace only the word "foo" with "bar", but not if "foo" is part of another word like "foobar".

These steps and tips should help you perform search and replace operations in Vim.

Resources