vim is one of the most popular file editors in Linux. Part of the popularity is due to the command line mode of vim, which enables users, especially software developers and advanced users to optimize time for file modification operations.

In this article, we will see how to find and replace text in vim command line mode.

First, let’s open a text file in vim:

vim test.txt

Vim operates in various modes. Two most important modes are the command mode mentioned above, and second is Insert mode, used to modify the file contents.

By default, when a file is opened, vim operates in command mode. You can press i to go to Insert mode.

In Command mode, you can directly start typing vim commands; they appear at the bottom of the terminal. This bottom part acts as an integrated command prompt in vim.

To search for a string, type backslash / followed by the string to be searched.

For example:
/dog

As seen above, it takes the cursor to the next occurrence of the string from the position where the cursor is placed. The cursor was placed at the string brown as shown in an earlier image. To find the next occurrences, press n. After the last occurrence, it goes back to first, giving a message “search hit BOTTOM, continuing at TOP”.

To search for a string with a special character, or for example characters like a plus (+), or a space, precede the character with a forward slash:

For example:
/C\+

To find and replace first string occurrence on a line, we place the cursor on that line, and use the following command:

For example:
:s/dog/tiger

As you can see in the screenshot above, the third-line where the cursor is placed, the word dog ha s been replaced with tiger as instructed in the command.

To find and replace all occurrences of string on a line, use /g at the end.

For example:
:s/cat/dog/g

To find and replace all occurrences globally, we use %s instead of only s:

For example:
:%s/dog/mouse

If the string consists of special character like space, it can be preceded by forward slash, same way as shown before.


🍻 Cheers!