If you work in a terminal environment, knowing how to efficiently find and replace in Vi / Vim is a fundamental skill. While its command-line nature might seem intimidating at first, it's incredibly powerful once you master the syntax. This guide will walk you through everything you need to know.
The Core Command: Substitute
The primary command for finding and replacing text in Vi/Vim is :substitute
, which can be shortened to :s
. The most common and useful form of this command replaces text across मौसम document.
First, ensure you are in Normal Mode (press `Esc` a couple of times). Then, type the following command and press `Enter`:
:%s/old_text/new_text/g
Breaking Down the Syntax
:
— Puts Vi/Vim into Command-Line Mode, allowing you to enter commands.%
— Specifies the range. `%` is a shortcut for "every line in the file."s
— The substitute command./
— The delimiter. It separates the parts of the command. You can use other characters like `|` or `#` if your text contains slashes.old_text
— The string or regular expression you want to find.new_text
— The string you want to replace it with.g
— A "global" flag. Without it, the command would only replace the first occurrence on each line. The `g` flag ensures it replaces all occurrences on every line.
Useful Modifiers (Flags)
You can enhance the substitute command by adding flags after the final delimiter. Here are the most essential ones:
Case-Insensitive Search (i)
To perform a case-insensitive replacement, add the i
flag. This is useful when you want to replace "apple", "Apple", and "APPLE" all at once.
:%s/apple/orange/gi
Confirmation Before Replacing (c)
If you're unsure about a replacement, the c
flag is your best friend. It will prompt you to confirm each change individually.
:%s/old_text/new_text/gc
Vim will highlight each match and ask you: `replace with new_text (y/n/a/q/l)?` (yes/no/all/quit/last).
When is Vi/Vim Not the Best Tool?
While powerful, the command-line approach has its limits. It can be cumbersome for:
- Multiple, unrelated replacements: If you have a list of 10 different words to replace with 10 different new words.
- Visual confirmation: When you need to see a clear "before and after" of your entire document without committing the changes.
- Non-programmers: The syntax can be unforgiving for users not accustomed to command-line tools.
A Simpler, Visual Alternative
For those complex tasks or for users who prefer a graphical interface, an online tool can be a lifesaver. Our free tool, Find and Replace Online, was built for this exact purpose.
You can paste your text, set up an entire list of find/replace pairs, and see the result instantly before copying it back. It offers the power of multiple replacements without the need to memorize command syntax.
Need to Replace Multiple Items at Once?
Give our free tool a try. It’s a powerful companion to your command-line skills.
Try Find and Replace Online