Vim search and replace

V

Search and replace. How do you do this in Vim?

The basics

%s stands for “substitute” here. In this example, we’re replacing all the occurrences of the “fn” string with “function” in the current line. The "g" flag at the end specifies that we need to do this globally, i.e. throughout the whole line.

Usually though you would want to replace in the whole line. For this case use ():

If you’re not quite sure you want to replace all the occurrences, then you can add a c flag. This will result in Vim asking you for every change before actually doing that.

Then in case you want to also catch words like “FN” and “Fn”, you can make the search case-insensitive by providing, you guessed it, another flag i.

The command is range-able which means you can specify a custom range of lines. Here’s how to run the search and replace for lines 5 till 10 (inclusive).

By this point you probably figured out how to run it for the whole file:

But that’s not all the magic. You can also use makers instead of the line numbers:

That range in the beginning of your command will also be predefined for you when you’re starting typing : in the visual mode. This is very helpful. In this case it will look somewhat like this:

Useful configurations for vimrc

There are several settings you may find useful. Simply put them into your .vimrc file.

Where to go from here?

Recent Posts

Categories

Meta