Replace character strings in editor vi

Hi everyone, today we are going to share how you can replace strings when working with the vi editor. In most cases that we have to work with UNIX environments, we do not have the graphic environment installed, and we need to edit text files. For this, one of the most used tools is the vi or vim editor.

Editor vi

To use the editor, all we have to do is call it with the name of the file we need to edit. If when you call it, the name of the file does not exist, a new file is created with the specified name.

When we run the command, the editor page opens.

Replace strings in vi

Find character strings in vi

There are two options for searching the editor.

To search from the cursor onwards:


To search from the cursor back:


In either case, the first appearance of “cadena_de_caracteres” is sought. You can go looking for the next appearance, you have to press the “n” key.

Replace strings in vi

There are several options to make substitutions with the vi editor, depending on the area where we want to make the substitution, the number of substitutions we want to make, etc.

To replace only on the current line, and only the first appearance of the searched string, the following command is used:


to replace all occurrences in the string a “g” is added to the end of the command


If you want to replace the entire file, all occurrences of the string:


If you only want to perform the replacement in a set of lines, and not in the entire file:


In the last two commands, if the “g” is not specified at the end, the first occurrence of the string on each line is changed.


An example of use for this utility can be if we have a tnsnames.ora for connections to an Oracle database, where each entry has, for example, an identifying suffix of a province, and we want to change all the suffixes at once.

BBDD_1_Madrid = (DESCRIPTION = ....

BBDD_2_Madrid = (DESCRIPTION = ....

BBDD_3_Madrid = (DESCRIPTION = ....

BBDD_4_Madrid = (DESCRIPTION = ....

BBDD_5_Madrid = (DESCRIPTION = ....

In this example there are several connections to the Madrid database. If you want to replace these connections from Madrid, with connections to the Lugo database, the command would be executed:


By executing the command, the file would look like this:

BBDD_1_Lugo = (DESCRIPTION = ....

BBDD_2_Lugo = (DESCRIPTION = ....

BBDD_3_Lugo = (DESCRIPTION = ....

BBDD_4_Lugo = (DESCRIPTION = ....

BBDD_5_Lugo = (DESCRIPTION = ....

You can consult the information of this tool in the official documentation of each UNIX or Linux distribution that is being used, but for us, who focus on databases, Oracle offers manuals for the use of commands, and you can find information about vi in the following link:

We hope you found it useful.


Database computer

If you don’t want to miss tricks like this and stay up to date with this world, subscribe to our newsletter. We will keep you informed with only one email per month.

Comments are closed.