Signup/Sign In
PUBLISHED ON: FEBRUARY 16, 2023

How to Find and Replace in Vim

vim is a code editor software based on ed, and an improvement to the editor VI, hence the name vim - "VI Improved". Contrary to most editors, vim has a few contrasting features, namely

  • a terminal/command-line editor
  • working on the concept of buffers, and
  • a modal editor

To understand the above things, vim is used via the terminal, by running the command vi / vim, hence a terminal editor. Any changes made are not autosaved, instead, it is like loading the file as a copy, and working on it, hence, the concept of buffers. The last point is what makes vim one of the most powerful, and frequently used editors, and why even after 30 years, and endless new options such as Atom, we still have vim.

Being a modal editor means that vim has various modes. When vim starts up, it loads into Normal mode, which is the root of all frustration for vim beginners. Normal mode is where we can use "vim grammar", enter other modes using predefined keys, such as command-line mode where a user can run built-in commands, or just as in modern editors, commands from plugins that have been installed by the user, or commands that the users have created.

On most *nix-based operating systems, vi/vim comes pre-installed, if not, you would find it available in your operating system package repos, or it can be downloaded from this site.

If you are struggling with exiting VIM, check out this tutorial. When you finally know how to save and exit VIM, it's time to get faster at editing files faster.

exit VIM meme

Vim find and replace Syntax

The best place to start in vim is always the vim documentation. It is comprehensive and covers every topic and point. Since we want to do a search and replace, the vim command for the same is the s[ubstitute] command. To enter command mode, we need to press the : key. Once in command mode, we run the following command :h :s, to get help on the substitute command. We get the output as follows

:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]
			For each line in [range] replace a match of {pattern}
			with {string}.
			For the {pattern} see |pattern|.
			{string} can be a literal string, or something
			special; see |sub-replace-special|.
			When [range] and [count] are omitted, replace in the
			current line only.  When [count] is given, replace in
			[count] lines, starting with the last line in [range].
			When [range] is omitted start in the current line.
							*E939*
			[count] must be a positive number.  Also see
			|cmdline-ranges|.

			See |:s_flags| for [flags].
			The delimiter doesn't need to be /, see
			|pattern-delimiter|.

Hence, the most basic usage of the command is :s/search/replace/. The {pattern}, is a regex pattern as defined by the vim regex engine, and can be read up on by using the command :h pattern.

Examples showing search and replace in vim

  1. Find and Replace on the current line

    • To replace only the first occurrence the command is of the form as defined as in the most basic usage.
      For example, if we want to replace the word raw with cook, we would use the command :s/raw/cook/.
    • To replace all occurrences on the current line, taking the example above, we append a g at the end giving us :s/raw/cook/g, where g means global.

    vim example s command

  2. Find and Replace in a range of lines

    • Show line numbers in VIM, check tutorial here.
    • vim has multiple ways of defining ranges, such as specifying line numbers, which means to edit lines 36 to 42, we would use 36,42, to edit from the current line to 13 lines ahead, we could write .,+13, where . represents the current line, or to edit the whole file we can use %. To know more about vim ranges use the command :h cmdline-ranges.
      Referring to the ranges above we get the following examples
      1. To substitute from 3 lines after the current line, till the end of the file we would write :.+3,$s/{pattern}/{string}/

      2. To substitute on the entire file, we would use :%s/{pattern}/{string}/

      3. To substitute from lines 35 to 46, the command becomes :35,46s/{pattern}/{string}/

    vim range s command

  3. Changing words only when they wholly match

    • vim matching by default would take even partial matches for substitution. Hence the search pattern being pat, it would even match the word pattern. To ensure only the word pat is substituted, we would wrap the word in between \<, and \>, giving us :s/\<pat\>/tap/
  4. Case Insensitive pattern matching

    • We would use the flag parameter and set it to i, giving us :s/{pattern}/{string}/i

    vim range s command

  5. Confirming the change

    • The flag parameter is set to c, giving us :s/{pattern}/{string}/c. On every successful match, there is a prompt, which can be replied to with a y, or an n, representing yes, and no. But we can also answer with l, meaning last, a, meaning change all successful matches after this, and this one.

    vim range s commandvim c flag s command

Conclusion

This tutorial covered how to search for a text in vim, and then replace that, using the :s command in vim.



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.