LinuxTools

Search and Replace in Vim

use vim editor

By Vlad, Monday, June 10th, 2024; 4 min read

Vi Improved (Vim), a widely used and license-free Linux text editor is a popular software thanks to its robust and all-round editing proficiency. The editor immensely excels in effective text alteration, especially through the Search and Replace feature. Vim enables the fundamental Search and Replace functionality within a file, allowing for advanced controls, like identifying slight matches or manipulating text in one line or within the entire document. Alongside its predecessor, Vi, Vim handles all tasks from the replacement of a single word to intricate find-and-replace operations that encompass the entire patterns. In this post, we’ll delve into the ‘Search and Replace’ function of Vim to teach readers how to make great edits and work efficiently with text. Before that, let’s begin with a brief overview of the search and Replace’ functionality.

What’s the Search and Replace function?

Learning text modification, such as simultaneous edits is very imperative when using text editing tools like Vim. The “Find” or “Search” function is a paramount operation for navigating through text, whether using slash characters to conduct specific searches, percentage characters to conduct whole-document operations, or uppercase characters to execute case-sensitive searches. In addition, the ability of the tool to identify literal strings and execute intricate searches refines its practicality, making the software a versatile, invaluable program for simple and advanced editing tasks. 

Search and Replace techniques in Vim

  1. Slash and Dot Command

Slash and Dot Command technique is recommended for single-instance text. This method constitutes the following steps:

  • A document is launched on Vim editor.
  • On the keyboard, the user presses the Slash (/) button/key.
  • The user hits the Esc button to return to standard mode.
  • The user types cgn then followed by the word/term they want to use for substitution.
  • The user reverts to the usual mode.
  • The user presses the n key to continue to the next instance of ‘find term.”
  • The user uses the period (.) button to replace the subsequent instance with the same replacement term.
  1. Substitute command (:s command)

This technique offers substantially greater versatility compared to the aforesaid slash and dot command method. Fundamentally, the substitute command or the :s command technique uses #:s/search_term/replacement_term/syntax to search for a defined ‘search_term’ inside the string where the cursor is placed, and replace it with a ’ replacement_term”. For example, if you would wish to search the word petrol in the current line and substitute it with diesel, use this syntax: 

# :s/petrol/diesel/

Then press the Enter key and the display will update and show that the syntax has substituted the term petrol with diesel

The utility of the substitute command method in Vim editor transcends the basic find and replace role to incorporate a myriad of functions, including options and flags. Its full command is: 

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

Using this command, users can combine supported flags to execute advanced search and replace operations. For example, users can add the g flag to pinpoint all instances of petrol in the current line: 

# :s/petrol/diesel/g

Then hit the Enter key to substitute the instances with Petrol. The user can add c flag to the syntax to “confirm” all the replacements:

# :s/petrol/diesel/gc

Moreover, Vim features countless other outstanding options that aid in text search and replacement. Examples include:

  • Pressing ‘Y’ to replace matches that have been selected. 
  • Pressing ‘n’ to skip the present match.
  • Choosing ‘a’ to substitute all matches altogether.
  • Using ‘I’ to substitute the present match and exit.
  • Pressing ‘q’ to halt the syntax when you are done.
  • Ctrl + E’to enable users to scroll up their screen quickly.
  • Ctrl + Y’to enable users to scroll down their screen quickly.

Key Takeaways

Prior to diving into the real-life examples of making use of the Search and Replace functions of Vim, users are advised to learn various fundamentals of the functionalities. These aspects include search range, case sensitivity, and word substitution, among others. 

  1. Search Range

The substitute command technique allows users to specify a range to stretch the tools’ functionality past the present line – set as the default range. That way, users can target specified lines to find and replace a pattern. To execute this, users can simply include the line numbers in the command and separate them by commas. For example, if they want to substitute all petrol instances with diesel between line 1 and line 3, they will use:

# :1,3s/petrol/diesel/g

The results displayed on the screen will indicate that all the instances of petrol (found between lines 1 and 3) have been successfully replaced with diesel.

Also, Vim users can use the percentage (%) symbol to go beyond a few lines range and add a ‘g’ flag to find and substitute a pattern across the entire text.

# :%s/petrol/diesel/g

Moreover, users can use ‘.’ Followed by ‘,’ and ‘$’ tofind and substitute terms from the current cursor position down to the end of the text 

# :.,$s/petrol/diesel/g
  1. Case Sensitivity

The tool’s search and replace function detects case distinction. Using the substitute command technique to replace petrol with diesel won’t be successful, especially if the term petrol has consistently been capitalized throughout the text. However, users can use a few handy methods to modify the command operation to be case-insensitive. This way, the editor won’t distinguish between upper and lowercase characters. For instance, adding a i flag to the syntax:

# :%s/petrol/diesel/gi
  1. Word Substitution

The default action of Vim’s :s command is to search patterns instead of specific, standalone terms matching those patterns. For example, if the user uses petrol as their search term (pattern), Vim will display all matches that have petrol, including petroleum. This implies running the syntax will inadvertently change patterns in other terms as well. To avoid this, users can use the symbols ‘<’ and ‘>’ to indicate the exact pattern (standalone word) that you intend to replace:

# :%s/\&lt;petrol\&gt;/diesel/gi

Final Thoughts 

Vim’s Search and Replace function is quite a helpful feature that assists you locate and replacing irrelevant terms and typos with properly written terms, promptly and efficiently. Besides, the tool is versatile and can be used to perform both simple and advanced modifications on text/documents.

Hi, I’m Vlad

Leave a Reply

Your email address will not be published. Required fields are marked *