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.
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
:1,$s/George Bush/Hillary Clinton/g
:1,$s/George Bush/John McCain/g
Here’s a brief explanation of how this vim search and replace command works:
:character says "put vim in last-line mode".
1,$means "from the first line of the file to the last line of the file".
scharacter means "'Swap' the first pattern (George Bush) with the second pattern (Barack Obama)".
gat 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 the
gthe string "George Bush" will only be replaced the first time it is found on a line.
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:
That vim search/replace command replaces the string "George Bush" with nothing, which is the same as deleting it.