vi/vim search and replace FAQ: How do I search and replace in vim?
A lot of people ask me how to perform a global search and replace operation in the vi (vim) editor. The vim editor is anything but intuitive, but for some reason I can remember this global search and replace syntax pretty easily.
A vim search and replace example
Going with the current U.S. election year theme, to search for every occurrence of the string “George Bush” and replace it with the names of any of the current candidates you'd just use one of the following vim search and replace commands:
:1,$s/George Bush/Barack Obama/g
or this
:1,$s/George Bush/Hillary Clinton/g
or this
:1,$s/George Bush/John McCain/g
vim search replace discussion
Here’s a brief explanation of how this vim search and replace command works:
- The
:
character says "put vim in last-line mode". - The string
1,$
means "from the first line of the file to the last line of the file". - The
s
character means "'Swap' the first pattern (George Bush) with the second pattern (Barack Obama)". - The forward slash characters enclose the pattern I'm trying to match. In this case it's a very simple sequence of characters, but it can also be a more complicated regular expression.
- The
g
at the end of the command says "Perform this command globally", where in this case "globally" means "for every occurrence you find on one line". If you don't include theg
the string "George Bush" will only be replaced the first time it is found on a line.
vim find and delete (search and delete)
Instead of using that syntax to perform a vim find and replace operation, you can also use it to perform a vim find and delete operation. For example, if you just want to delete every occurrence of the string "George Bush" in your current file, just use this command:
:1,$s/George Bush//g
That vim search/replace command replaces the string "George Bush" with nothing, which is the same as deleting it.