Search and replace a word in a file using Vim editor

There are many times when you want to replace multiple occurrences of a word in a file with another word. In small files you can do it manually. But in large files, you can’t take on that method. Vim editor provides a simple command to do this. Say you want to replace a word ‘begin‘ with the word ‘end‘ from a file ‘test‘.

In the terminal,

vim test

Once you have the file opened, simply type this command

:%s/begin/end/g

This command will replace all the occurrences of ‘begin‘ with ‘end

Advertisements

3 responses to “Search and replace a word in a file using Vim editor

  1. When you have problem with escaping the slashes in the search or replace you can use :%s:search:replace:g(c) or any other delimiters among @ % ; instead of /

  2. I’m a fan of Vim, but it is intended for interactive editing. The same operation can be accomplished with: sed -i -e ‘s/begin/end/g’ file1 [file2…]

    This offers the advantage of editing multiple files at once.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s