How to replace text in multiple lines in Vim
Editing multiple lines at once can make you extra productive.
In order to be efficient in Vim, you need to learn how to replace multiple strings on different lines at once. In other IDEs such as sublime or VsCode, these are done via multi-line and multi-cursor editing. In Vim, it’s done via a simple command. In this post, we will explore different scenarios where you may need it.
Replacing text on the current line
To replace a text in the same line as the cursor, you can use the following:
:s/foo/bar/g
Typing this command will replace `foo` to `bar` in the current line.
The g at the end stands for ‘global’ meaning change all occurrences within the same line. If you remove it, it will only update the first occurrence.
Replacing a string within the whole file
To replace a text within the entire file, you can add a % in the beginning of the previous command:
:%s/foo/bar/g
This command will replace foo
to bar
in every line and occurrence.
Replace a string on multiple lines
For example, to replace `foo` with `bar` in line 2 and 5:
:1s/foo/bar/ | 2s/foo/bar/ | 5s/foo/bar/
This command tells Vim to substitute `foo` to `bar` on 1st, 2nd, and 5th line.
Replace a string on multiple lines within a range
You can specify a range to change a string within that range by simply stating the beginning and end line numbers. For example, to change `foo` to `bar` within lines 4 to 7, you can do so with:
:4,7s/foo/bar/g
The dot (.) represents the current line, so if you want to change the current line + 3 more lines, you can do so by:
:.,+2s/foo/bar/g
The dollar sign ($) represents the last line, so if you want to change text starting from the current line all the way to the end of the file, you can use:
:.,$s/foo/bar/g
However, the easiest way to do this by first selecting the area using Visual Mode.
You can press V to enter the Visual Mode and select the lines you’re interested to replace the text in. After than press the colon (:) to enter command mode. You will notice a ‘<,’> in the prompt. Just type your substitution command after these tags.
‘<,’>s/foo/bar/g
Final Thoughts
You can do a lot with Vim when it comes to searching and replacing text. We have only covered the tip of the iceberg on this tutorial, just enough to cover basic scenarios to keep you moving and productive.