Find and Replace in Vim and Vi

find and replace vim

Vim, renowned for its robust and versatile editing capabilities, excels in efficient text manipulation, particularly through its find and replace function. 

This powerful feature facilitates the basic find and replace vim tasks within a document and allows for intricate control, such as pinpointing partial matches or modifying text in a single line or across the entire file in Vim. 

Vim and its improved version, Vi, can handle everything from a single word replacement to advanced search-and-replace operations encompassing entire patterns. 

In this tutorial, we will focus on Vim and Vi find and replace features to help you work with text patterns and make more efficient edits. Let’s start with a short overview of this functionality.

Table Of Contents

  1. An Introduction to Find and Replace in Vim and Vi
  2. Two Easy Ways of Searching and Replacing Text in Vim
    1. Slash and Dot Command in Vim and Vi
    2. Substitute Command
  3. Key Points to Keep in Mind for Find and Replace Operations
    1. Search Range
    2. Case Sensitivity for Basic Search and Replace
    3. Word Substitution
  4. The Find and Replace History in Vi and Vim
  5. Find and Replace Examples
    1. Example #1: Find and Replace Entire Lines
    2. Example #2: Add a New Entry in a Numbered List
    3. Example #3: Remove Double Spaces
    4. Example #4: Replace Several Words with a Single Word
  6. Delete All Pattern Occurrences
  7. Conclusion
  8. FAQs

An Introduction to Find and Replace in Vim and Vi

Mastering text manipulation, including simultaneous edits, is essential when using Vim or its predecessor, Vi.

Vim, a widely used Linux text editor, provides a variety of efficient methods to locate and substitute words swiftly.

The search operation is a crucial aspect of navigating through content, whether with the slash character for specific searches, the percentage character for whole-file operations, or uppercase characters for case-sensitive needs. 

Additionally, Vim’s capability to recognize literal strings and conduct advanced searches enhances its utility, making it an invaluable tool for both simple edits and complex coding tasks. 

Two Easy Ways of Searching and Replacing Text in Vim

Vim facilitates navigation and modifications in large files by enabling the search and replacement of text patterns.

In particular, Vim provides two methods for searching and replacing text, tailored to either a singular modification or numerous edits.

Slash and Dot Command in Vim and Vi

We recommend using the slash and dot commands for single-instance text substitution in Vim.

Launch a document in Vim and proceed with the following steps:

  • Hit the Slash key (/).
  • Enter the word you wish to find to highlight it within the document and press Enter.

vi eidtor

  • Press the Esc key to revert to normal mode.
  • Type cgn followed by the term you wish to use for replacement.

vim editor

  • Return to the Standard mode.
  • Press n to proceed to the subsequent instance of the search term.

vi editor 1

  • Use the Period (.) key to substitute the next instance with the identical replacement term.

vim editor 1

Substitute Command

The :s command offers greater versatility than the slash and dot command.

The fundamental syntax for the :s command is:

# :s/search_term/replacement_term/

The command looks for the specified search_term in the line where the cursor is positioned. The :s part of the command then substitutes the found search_term with the replacement_term.

For instance, if you want to locate the term vi in the current line and replace it with Vim, use this command:

# :s/vi/Vim/

vi editor 2

Press Enter, and the terminal display updates, showing that the command has replaced the string vi with Vim:

vim editor 2

The scope of the :s command extends far beyond a simple search and replace functionality. It incorporates a variety of options and flags. The full syntax of the substitute command is as follows:

# :[range]s/search_term/replace_term/[flags] [count]

You can execute complex search and find operations by combining the supported flags. For instance, use the g flag to locate every instance of vi in the current line.

# :s/vi/Vim/g

vi editor 3

Press Enter to replace both instances with Vim:

vim editor 3

You can also “confirm” each substitution by adding the c flag to the command:

# :s/vi/Vim/gc

vi editor 4

Here’s how the output of the command looks like: 

vi editor 5

When using Vim, you’ve got some excellent options while substituting text. Here’s what you can do:

  • Press Y to substitute the match you’ve selected.
  • Hit n if you want to skip the current match.
  • Choose a to replace all the matches in one go.
  • Press q to stop the command if you’re done.
  • Use I to replace the current match and then quit.

Some Vim implementations offer additional options like ^E and ^Y for scrolling. Here’s how they work:

  • Scroll up your screen quickly with Ctrl + E.
  • Scroll down just as smoothly with Ctrl + Y.

Key Points to Keep in Mind for Find and Replace Operations

Before we dive into the examples of using the find and replace capabilities of Vi and Vim, it is important to understand the critical aspects of these functionalities. You need to remember these aspects while using search and replace operations. 

Search Range

When using the :s command for search and replace, you can extend its functionality beyond the current line (the default range) by specifying a range. Here’s how to do it:

  • You can target specific lines for finding and replacing a pattern. For this, simply add the line numbers separated by a comma. For instance, if you want to replace every instance of vi with Vim from line 1 to line 3, here’s how you’d do it:

# :1,3s/vi/Vim/g

vi editor 6

The displayed results indicate that just the initial two occurrences of vi (found within the top three lines) were successfully modified to Vim:

vim editor 4

You can go beyond the three lines by using the % symbol and adding the g flag to search and replace a pattern throughout the file.

# :%s/vi/Vim/g

vim editor 5

Replace the entire text from the current line down to the last line with a dot (.), followed by a comma, and then a dollar sign ($).

# :.,$s/vi/Vim/g

vi editor 7

Since we’re looking at the final line, it’s clear that the instances of vi in this last line have been successfully modified.

vi editor 8

You can easily add or subtract lines from your current position by using the +/- symbols and numbers. For instance, if you want to replace vi with Vim not just on the current line but also on the following two lines, you simply type:

# :.,+2s/vi/Vim/g

vim editor 6

Case Sensitivity for Basic Search and Replace

You should know that the find and replace functionality in Vim is sensitive to case distinctions by default. So, if you’re using the :s command to try replacing vim with vi, it won’t be effective, especially when Vim is consistently capitalized in your document. In such cases, searching for Vim rather than vi is a better strategy.

If you need the find-and-replace operation to be case-insensitive, you can use a couple of handy methods. 

One simple approach is to incorporate the i flag in your command. This way, Vim won’t differentiate between uppercase and lowercase characters when matching patterns during the search and replace process.

# :%s/vim/vi/gi

vi editor 9

As you can see, the two instances of Vim in the output have been successfully located and replaced with vi

We strongly recommend using the I flag to re-enable case-sensitive searching.

Alternatively, you can add \c at the end of the search pattern.

# :%s/vim\c /vi/g

vim editor 7

The results indicate that regardless of the search term being in lowercase, the command successfully identifies Vim with uppercase V in the text.

When done, activate the case-sensitive search feature by appending /C to the next search pattern.

Word Substitution

In the :s command, the default behavior is to look for patterns rather than specific, standalone words that match the pattern. For instance, if you use vi as the search pattern, it will find matches in any part of a word where vi appears, like in visible.

vi editor 10

Running the command on the entire text may inadvertently alter patterns found in other words too.

vim editor 8

You can carry out search and replace for a whole word with the following command syntax:

# :%s/\<search_term\>/replace_term/

The < symbol denotes the start, while the > symbol indicates the end of a word. For instance, if you want to find the standalone word vi (excluding cases where it is part of a larger word like visible) and replace it with Vim, you would proceed as follows:

# :%s/\<vi\>/Vim/g

vim editor 9

The Find and Replace History in Vi and Vim

Executing the :s command alone displays a history of previous find and replace (substitution) operations.

Additionally, when you execute the :s command, you can navigate through the document using the Up and Down arrow keys.

More importantly, the :s command can be used to reapply past substitutions to new text. For instance, if the history indicates that the command was used to replace every occurrence of vi with Vim, you can reapply this without going through all the steps of finding the pattern and replacing all occurrences.

When you run :s, it not only locates previously made substitutions but also identifies all instances of vi that have not been altered yet.

vi editor 11

Find and Replace Examples

The find and replace feature in Vim is highly practical and versatile. 

Let’s see some examples of common substitute operations that you can try in Vi and Vim.

Example #1: Find and Replace Entire Lines

The find and replace feature in Vim is highly practical and you can easily replace the lines in the text. For instance, try the following command:

# :%s/^The best  .*/ Learn more about Vim!/g

vim editor 10

The caret symbol (^) signifies the start of a line, while the asterisk (*) represents the rest of the line.

vim editor 11

Example #2: Add a New Entry in a Numbered List

Inserting an item in the middle of a numbered list in Vim requires the user to adjust the numbering for all following items.

The substitute command modifies the numbering of all subsequent articles. For instance, consider this command:

# :5,$s/\d\+/\=submatch(0) + 1/

The command is structured as follows:

:5,$ specifies the range, starting from the fifth line to the end of the document.

\d\+ identifies the pattern to search for, which in this case is a sequence of one or more digits.

\=submatch(0) + 1 is used for replacement, where each found number is incremented by 1.

Example #3: Remove Double Spaces

You can easily add double spaces as a common typing mistake, especially when speed-typing. The good thing is that you can easily resolve the issue using the :s option in the following command:

# :%s/[double space]/[single space]/g

vim editor 12

As you can see, the double spaces in the last line have become single spaces after the execution.

vim editor 13

Example #4: Replace Several Words with a Single Word

Use the substitute command to replace multiple search terms with a single term. For instance, you can replace every occurrence of vi and Vim with This text editor.

# :%s/\(vi\|Vim\)/This text editor/g

vim editor 14

text editor

Delete All Pattern Occurrences

To remove a specific term without replacing it, simply omit the replacement term. For instance, to eliminate every occurrence of Vim, you would proceed as follows:

# :%s/Vim/

editor

Conclusion

Mastering Vim and Vi find and replace feature — from basic text replacement to complex pattern matching with regular expressions—significantly enhances editing efficiency and deepens your grasp of Vim’s capabilities. 

Essential operations, such as case-insensitive searches, handling first occurrences, and using the substitute command, provide flexibility in editing tasks, whether it’s a single line, an entire file, or specific text in Vim. 

RedSwitches offers the best dedicated server pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What is Vim?

 Vim is a highly configurable text editor built to enable efficient text editing and supports various plugins for additional functionality.

Q. How can I perform a basic search and replace in Vim?

 To perform a basic search and replace in Vim, you can use the :s command followed by the pattern to search for and the replacement string. For example, to replace all occurrences of “foo” with “bar” in the entire file, you can use the command :%s/foo/bar/g.

Q. How can I substitute a whole word in Vim?

 You can substitute a whole word in Vim by using the `:s` command followed by the pattern to search for and the replacement string, using `\b` to match the beginning and end of the word. For example, to replace all occurrences of the word “old” with “new”, you can use the command :%s/\/new/g.

Q. What are some special cases when performing a search and replace in Vim?

 Special cases when performing a search and replace in Vim include using special characters, the g flag to replace all occurrences on a line, and using the & command to repeat the previous substitution command.

Q. How can I use visual selection in Vim for search and replace?

 You can use visual selection in Vim for search and replace by first entering visual mode, selecting the text to modify, and then executing the substitution command with :s followed by the replacement string.

Q. What is the syntax for performing a search and replace in a specific range of lines in Vim?

 To perform a search and replace in a specific range of lines in Vim, you can use the command :startline,endline s/pattern/replacement/g, where `startline` and `endline` represent the range of lines to apply the search and replace command to.

Q. Can I perform a case-insensitive search and replace in Vim?

 Yes, you can perform a case-insensitive search and replace in Vim by appending the i flag to the substitution command. For example, to perform a case-insensitive search and replace for “foo” with “bar”, you can use the command :%s/foo/bar/gi.

Q. Are there any plugins available for enhancing the search and replace functionality in Vim?

 Yes, there are various plugins available for enhancing the search and replace functionality in Vim, such as the replace-motion plugin that provides additional movements for the search and replace command.

Q. How can I substitute a single character or a character range in Vim?

 You can substitute a single character or a character range in Vim by using the `.` to match any single character and specifying a range using `[a-z]` to match any characters within the specified range.

Q. What is the command to perform a search and replace while asking for confirmation first in Vim?

 The command to perform a search and replace while asking for confirmation first in Vim is `:%s/pattern/replacement/gc`, where the `c` flag prompts for confirmation before making each substitution.