Skip to main content

Delving into Search and Replace in VI Editor: An Extensive Guide

The VI editor is famed for its efficiency, and mastering search and replace functionality is quintessential for leveraging its full potential. This article will delve deep into these fundamental aspects of VI, starting from the basic search to the advanced levels of global search and replace.

Creating a Sample Text File

Before embarking on this journey, let’s create a sample file with few lines of text:

vi search_replace_sample.txt

In VI, press i to enter Insert Mode and type:

One apple a day,
keeps the doctor away.
Bananas are rich in potassium.
Oranges are a good source of Vitamin C.

Press Esc to exit Insert Mode, and type :wq to write and quit the file.

Basic Searching in VI

  • To search for a text string in VI, type / followed by the string you are searching for, and press Enter.
  • Example: /apple will highlight the word apple in the text.

2. Navigating Search Results

  • To navigate through occurrences, press n for the next occurrence and N for the previous occurrence.

Advanced Search and Replace

Basic Replacement

To replace a single occurrence of a string on the current line:

:s/old_string/new_string/

Example: :s/apple/fruit/

Global Replacement on a Line

To replace all occurrences of a string on the current line:

:s/old_string/new_string/g

Example: :s/a/A/g will replace all lowercase ‘a’ with uppercase ‘A’ on the current line.

Global Replacement Throughout the File

To replace all occurrences of a string throughout the file:

:%s/old_string/new_string/g

Example: :%s/day/night/g will replace all occurrences of ‘day’ with ‘night’ throughout the file.

Confirming Each Replacement

To confirm each replacement throughout the file:

:%s/old_string/new_string/gc

Example: :%s/orange/fruit/gc will ask for confirmation before replacing each occurrence of ‘orange’ with ‘fruit’.

Advanced Global Replacement

  • Replacing across a range of lines.
    :[start_line],[end_line]s/old_string/new_string/g

Example: :1,2s/a/A/g will replace all occurrences of ‘a’ with ‘A’ between lines 1 and 2.

Conclusion

Mastering search and replace in VI is crucial for anyone wanting to exploit VI to its fullest. The capabilities of search and replace in VI go far beyond simple text manipulation, offering a wide array of functionalities from basic string replacement to advanced global modifications across specified line ranges, providing users with extensive control and precision in their text editing endeavors. By understanding and utilizing these features, users can significantly enhance their efficiency and accuracy in text management within the VI editor.

What Can You Do Next 🙏😊

If you liked the article, consider subscribing to Cloudaffle, my YouTube Channel, where I keep posting in-depth tutorials and all edutainment stuff for software developers.

YouTube @cloudaffle