Most of the vim users know this this command: :% s/old/new/g. It’s a simple replace all old with new, it’s a regular expression based substitution with the g flag and % means do it on the whole file.

We can use any ranges instead of %. We can use the previously used :'<,'> s/old/new/g to do it on a visual selected section, we can use exact line numbers like :10,33 s/old/new/g, or we can use relative line numbers like :-10,. s/old/new/g which will replace all old with new between the cursor and 10 lines above the cursor. Without a range, it operates on the active line.

That’s for the range part, what about the flag? We can use a lot more than g. Here is a list of useful flags:

  • c: Confirm each substitution. It can be very useful if we want to replace some of them, but not all of them.
  • g: Replace all occurrences in the line.
  • i: Ignore case for the pattern.
  • I: Don’t ignore case for the pattern. It’s useful if vim is configured to ignore case by default.

A lesser known fact, we can omit the old part if we did a search before. If it’s empty, substitute will use the last search value as pattern. So we search for old with /old, reviewed it and we want to replace all of them, we can simply call :% s//new/g.