Vim Search and Replace String

Vim is a powerful text editor that offers various functionalities for searching and replacing strings within your text. Here are different ways to perform string replacements using Vim’s command mode:

Replace String on Selected Line

To replace a string on the currently selected line, you can use the :s command. For instance, to replace all occurrences of “foo” with “bar” on the selected line, you can use the following command:

1
:s/foo/bar/g

This will replace all occurrences of “foo” with “bar” on the selected line.

Replace String on All Lines

To replace a string on all lines in the file, you can use the % symbol with the :s command. For example, to replace all occurrences of “foo” with “bar” on all lines, you can use the following command:

1
:%s/foo/bar/g

This command will replace “foo” with “bar” on every line in the file.

Replace String on All Lines With Prompt

If you want to be prompted for confirmation before each replacement on all lines, you can add the c flag to the :s command. This will make Vim ask you whether to replace the string on each occurrence. Here’s how you can do it:

1
:%s/foo/bar/gc

When you execute this command, Vim will display each occurrence of “foo” on every line and ask if you want to replace it with “bar”. You can choose ‘y’ to replace, ’n’ to skip, ‘a’ to replace all remaining occurrences, or ‘q’ to quit the replacement process.

Remember that Vim has various modes (normal, insert, visual, etc.), and these commands are used in the normal mode. Make sure you are in the appropriate mode before using these commands.

Keep in mind that Vim has a learning curve, so it might take some time to get used to its features.

0%