Skip to main content
vim

Replace Text Using VIM

By October 7, 2016September 12th, 2022No Comments

Replace Text Using VIM Manually or Globally

Replace Text Using VimWhen working with text files we often need to be able to select text and replace the values. Working with the example we use, we have a Puppet manifest and we need to replace text using vim to correct variable names.  For us, we want to look for the service variable and replace it with a more descriptive ntp_service identifier.


Replace Globally

VIM does allow us to substitute text easily through the whole document. For the range of lines that we are wishing to work with, we specify %. Meaning the whole document. This is run from the colon prompt or EX mode.

:%s/service/ntp_service/

This searches the whole document for service and substitutes the string with ntp_service. Whilst this is OK is does prove to make too many changes. Reversing the change is easy using the command u in normal mode.

Manual Selection Made Easy

We can make manual selections very easily just moving to the s of the first occurrence of service and using *. This will select all occurrences of the string service. If they are not highlighted we can enable highlighting in EX mode using:

: set hls

Make the Change and Repeat

With the service selected we can enter insert mode using i. We then need to add in the text we need:- ntp_ and ESC. This counts as a change in VIM and is repeatable. We just need to navigate to the next occurrence and use the command . to repeat.

The video steps you through this process: