How do I find and replace in Vim?
- User
How do I find and replace in Vim?
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How do I find and replace in Vim?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In Vim, you can perform find and replace operations using the :substitute command (often abbreviated as :s). Below is a detailed guide on how to use it effectively:
The general syntax for the :substitute command is:
:%s/old/new/g
:%s: Performs the substitution on all lines in the file. (Without %, it only works on the current line.)old: The text you want to find (can be a word, phrase, or regular expression).new: The text you want to replace it with.g: Performs the replacement globally on each line (without g, it only replaces the first occurrence on each line).Replace a word on the current line only
To replace the first occurrence of "foo" with "bar" on the current line:
:s/foo/bar
Replace a word globally on the current line
To replace all occurrences of "foo" with "bar" on the current line:
:s/foo/bar/g
Replace a word in the entire file
To replace all occurrences of "foo" with "bar" in the entire file:
:%s/foo/bar/g
Case-sensitive replacement
Vim is case-sensitive by default. To replace "Foo" with "Bar" (exact match):
:%s/Foo/Bar/g
Case-insensitive replacement
To ignore case during the replacement (e.g., replace "foo", "Foo", or "FOO" with "bar"):
:%s/foo/bar/gi
Here, i stands for "ignore case."
Confirm each replacement
To be prompted for confirmation before each replacement (press y to confirm, n to skip):
:%s/foo/bar/gc
Here, c stands for "confirm."
Replace within a specific range of lines
To replace "foo" with "bar" only between lines 5 and 10:
:5,10s/foo/bar/g
Replace using regular expressions
You can use regular expressions in the search pattern. For example, to replace all occurrences of "color" or "colour" with "hue":
:%s/colou\?r/hue/g
Here, \? makes the "u" optional in the pattern.
Escape special characters
If your search or replacement text contains special characters (e.g., /, ., *), you need to escape them with a backslash (\). For example, to replace "a/b" with "c/d":
:%s/a\/b/c\/d/g
Use an alternate delimiter
If your search or replacement text contains many slashes, you can use a different delimiter (e.g., # or |) to make the command more readable. For example:
:%s#a/b#c/d#g
Undo a replacement
If you make a mistake, you can undo the last change by typing:
:u
Preview changes
Vim doesn't have a built-in preview feature, but using the c flag (confirm) allows you to review each change before applying it.
Search without replacing
To search for a pattern without replacing it, use the / command:
/foo
Press n to go to the next occurrence and N to go to the previous one.
Use captured groups in replacements
You can use regular expressions to capture parts of the matched text and reuse them in the replacement. For example, to wrap all numbers in parentheses:
:%s/\(\d\+\)/({\1})/g
Here, \(\d\+\) captures one or more digits, and \1 refers to the captured group in the replacement.
Here’s a summary of the most common flags you can use with :s:
g: Replace globally on each line.i: Ignore case during the search.c: Confirm each replacement.I: Force case-sensitive search (overrides ignorecase setting).If you frequently need case-insensitive searches, you can set Vim to ignore case by default by adding this to your ~/.vimrc:
set ignorecase
You can also enable "smart case" (case-insensitive unless the search contains uppercase letters) with:
set smartcase
The :substitute command is very powerful in Vim, especially when combined with regular expressions and ranges. Practice the examples above, and you'll quickly get the hang of it!
In Vim I can search using /. I want to replace one at a time using / just to be safe. Is this possible?
Yes, it is possible to search using / and replace occurrences one at a time in Vim, ensuring you have full control over each replacement. While the :substitute command with the c (confirm) flag is the most common way to do this, you can also combine searching with / and manual replacement in a workflow. Below, I'll explain how to achieve this safely and efficiently.
/ to Search and :s to Replace One at a TimeSearch for the pattern
Use / to search for the text you want to replace. For example, to search for "foo":
/foo
Press Enter to jump to the first occurrence. Use n to move to the next occurrence and N to move to the previous one.
Replace the current occurrence
When you're on an occurrence you want to replace, use the :s command to replace only that specific occurrence on the current line. For example, to replace "foo" with "bar":
:s/foo/bar
This replaces only the first "foo" on the current line, starting from the cursor position.
Move to the next occurrence
After replacing, press n to jump to the next occurrence of "foo" and decide whether to replace it by running :s/foo/bar again.
Repeat as needed
Continue this process (n to search, :s/foo/bar to replace) until you've reviewed and replaced all occurrences you're interested in.
:substitute with Confirmation (c Flag)If you want a more streamlined approach, you can use the :substitute command with the c flag, which prompts you for confirmation on each replacement. This method doesn't require manually searching with /, but it still allows you to review each change:
Run the substitution with confirmation
To replace "foo" with "bar" in the entire file, with a prompt for each occurrence:
:%s/foo/bar/gc
% applies the command to the entire file.g ensures all occurrences on each line are considered.c prompts you to confirm each replacement.Respond to prompts
For each occurrence, Vim will highlight the match and prompt you with options:
y (yes): Replace this occurrence.n (no): Skip this occurrence.a (all): Replace all remaining occurrences without further prompts.q (quit): Stop the replacement process.l (last): Replace this occurrence and then quit.^E (scroll up) or ^Y (scroll down): Adjust the view if the prompt is off-screen.This method is safer and more efficient than manually searching and replacing, especially for large files, because it automates the process of moving between occurrences while still giving you control.
If you want to combine the flexibility of searching with / and the power of Vim's macros, you can record a macro to search and replace one occurrence at a time. This is useful if you need to perform additional checks or actions during the process.
Start recording a macro
Press q followed by a register name (e.g., q) to start recording a macro. For example:
qq
Perform the search and replace
While recording, do the following:
/foo<CR> (where <CR> is the Enter key).:s/foo/bar<CR>.End the macro
Press q again to stop recording:
q
Replay the macro
To apply the macro to the next occurrence, press @q. You can repeat this as many times as needed by pressing @q again or using a count (e.g., 5@q to apply it 5 times).
This method is particularly useful if you want to perform additional actions (e.g., visually inspect the line) before deciding to replace.
| Method | Pros | Cons |
|---|---|---|
| Method 1 (Manual) | Full control, simple to understand | Tedious for many replacements |
| Method 2 (Confirm) | Efficient, built-in safety, less typing | Less flexible for complex workflows |
| Method 3 (Macro) | Customizable, repeatable, powerful | Requires learning Vim macros |
For most use cases, Method 2 (using :substitute with the c flag) is the safest and most efficient way to replace one occurrence at a time while reviewing each change. It combines the search and replace steps into a single command and provides a clear, interactive interface for confirming changes.
If you prefer to stick with / for searching (e.g., because you're already comfortable with it or need to visually inspect each match before deciding), Method 1 is a good choice, though it requires more manual effort.
Highlight matches
To make it easier to see all occurrences of the search pattern, enable search highlighting by adding this to your ~/.vimrc:
set hlsearch
Or enable it temporarily with:
:set hlsearch
You can clear the highlighting with :nohlsearch (or :noh for short).
Case sensitivity
If you want to search and replace case-insensitively, add the i flag to your :s command (e.g., :%s/foo/bar/gci) or set ignorecase globally in your ~/.vimrc:
set ignorecase
Undo mistakes
If you accidentally replace something, you can undo the last change by pressing u in normal mode.
By using one of these methods, you can safely replace text one occurrence at a time while leveraging the power of Vim's search capabilities.