|
Lots of people ask me how to do global replacements of strings in the vim editor. Of course vi 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 replace every occurrence of the string "George Bush" with the names of any of the current candidates you'd just use one of the following 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
Here's a brief explanation of how that command works:
- The
: character says "put vi 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 the g the string "George Bush" will only be replaced the first time it is found on a line.
Find and delete
Instead of using that syntax to perform a find and replace operation, you can also use it to perform a 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 command replaces the string "George Bush" with nothing, which is the same as deleting it.
|