find and replace in vi editor

How to Find & Replace String in VI Editor

VI Editor allows you to easily substitute strings & patterns with another string. Sometimes you may need to search and replace strings in your documents. For such purposes, VI editor is a very useful tool. In this article, we will look at how to find & replace string in VI Editor.

How to Find & Replace String in VI Editor

Open vi editor and be in normal mode (default mode) to be able to substitute strings. Press Esc key to go into normal mode.

Here is the general syntax for string substitution in vi editor.

:[range]s/{pattern}/{string}/[flags] [count]

The command searches each line in [range] for {pattern} and replaces it with {string}, [count] number of times. You may decide to replace all occurrences, or do a case insensitive match using different [flags].

If you do not mention [range] and [count] vi editor will replace the pattern in current string, where your cursor is located.

Here is a simple example to replace first occurrence of ‘today’ with ‘tomorrow’ in the current line.


Add g flag to replace all occurrences of search pattern with string, in the current line.


If you want to the pattern to be replaced throughout the file, add % at the beginning of your command as shown.


If you omit new string, it is treated as empty string and the given pattern is deleted


You may also use other characters as delimiters, instead of /. For example, if you have / character in search pattern or substitution string, you may use | as delimiter.


If you want a confirmation before each substitution, add c flag as shown below


By default, substitution is case sensitive. If you want case insensitive substitution, use i flag as shown below.


If you want to search & replace string only in specific range of lines such as lines 5-20, mention it at the beginning of your command, as shown below.


Please note that the above range includes line 5 and line 20. You may also use special characters like dot(.) to indicate current line, and $ to indicate the last line.


You may also specify range using offsets +/-. Here is an example to specify range starting from line 5 and for a range of next 4 lines.


By default, vi editor will substitute patterns even if they are part of another word. If you want to substitute the whole word exactly and not a part of the word, enclose your pattern in \< and \>. Here is an example


In the above statement, vi editor will replace today only if it is not embedded in another word. For example, the above command will not replace today in “today’s” but will replace it in “today is a nice day”.

In this article, we have looked numerous ways to search & replace strings in vi editor.

Also read:

How to Find Parent Process ID in Linux
How to Change Default Shell in Linux
How to Install Moodle with NGINX in Ubuntu
How to Download File in Python
How to Run CGI Script in Apache

Leave a Reply

Your email address will not be published.