How to find and replace text in Vim or Vi
How to find and replace text in Vim or Vi
Find and replace text in Vim or Vi
Vim is a popular text editor among system administrators and developers. Most Linux Distros come pre-installed. You can use various shortcuts to easily edit your code in Vim. In this tutorial, you will learn how to find and replace text in Vim or Vi.
Basic search and replace syntax in Vim
The basic syntax for Vim search and replace is:
:%s/SEARCH_TEXT/REPLACE_TEXT/COMMAND_FLAG
In the syntax above,SEARCH_TEXT: The text to search for.REPLACE_TEXT: Replacement text.COMMAND_FLAG: Various flags used during search and replace.
1. Find and replace current word
You can use the following command to replace all the specific words on the current line.
:s/SEARCH_TEXT/REPLACE_TEXT/g
2. Find and replace words in every line
You can use the following command to replace all occurrences of a particular word on all lines.
:%s/SEARCH_TEXT/REPLACE_TEXT/g
3. Find and replace case-sensitive words
using i
Flag that can replace case-sensitive words. You can use the following commands to find and replace case-sensitive words.
:%s/SEARCH_TEXT/REPLACE_TEXT/gi
4. Find and replace words between specific line ranges
You can also use the following commands to find and replace words within a specific line number range.
:RANGE_STARTS_AT,RANGE_STARTS_AT s/SEARCH_TEXT/REPLACE_TEXT/g
4. Find and replace words asking for confirmation
using c
Flag asking for confirmation before replacing text.
:%s/SEARCH_TEXT/REPLACE_TEXT/gc
Conclusion
In this tutorial, you learned how to find and replace text in Vim or Vi. If you have any questions about this, please comment below.