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:
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.
Esc to exit Insert Mode, and type
:wq to write and quit the file.
Basic Searching in VI
1. Initiating a Search
- To search for a text string in VI, type
/followed by the string you are searching for, and press
/applewill highlight the word apple in the text.
2. Navigating Search Results
- To navigate through occurrences, press
nfor the next occurrence and
Nfor the previous occurrence.
Advanced Search and Replace
To replace a single occurrence of a string on the current line:
Global Replacement on a Line
To replace all occurrences of a string on the current line:
:s/a/A/g will replace all lowercase ‘a’ with uppercase ‘A’ on the
Global Replacement Throughout the File
To replace all occurrences of a string throughout the file:
:%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/orange/fruit/gc will ask for confirmation before replacing each
occurrence of ‘orange’ with ‘fruit’.
Advanced Global Replacement
- Replacing across a range of lines.
:1,2s/a/A/g will replace all occurrences of ‘a’ with ‘A’ between
lines 1 and 2.
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.