0.1 The Detective’s Magnifying Glass
Imagine you’re a detective with a magical magnifying glass that can: - Find any clue instantly across thousands of pages - Transform evidence with a single command - Replace every occurrence of a pattern simultaneously - Show you exactly what will change before you commit
That’s Vim’s search and replace system! It’s like having a find-and-replace superpower that works at the speed of thought.
0.2 The Two-Phase Process
Vim’s search and replace follows a simple pattern:
- Search Phase: Find what you’re looking for
- Replace Phase: Transform what you found
The Magic Formula:
Think of it as: “substitute old_pattern with new_pattern”
0.3 Basic Search: Finding Your Target
0.3.1 Simple Search Commands
| Command | What It Does | Story |
|---|---|---|
/pattern |
Search forward | “/ means search ahead” |
?pattern |
Search backward | “? questions search behind” |
n |
Next match | “next result” |
N |
Previous match | “Next backward” |
* |
Search word under cursor | “***** highlights this word” |
# |
Search word backward | “# searches this word backward” |
0.3.2 Practical Search Examples
Example 1: Finding a function
Task: Find the calculate_tax function 1. /calculate_tax - Search for the function 2. Enter - Execute search 3. n - Jump to next occurrence (if any)
Example 2: Finding all occurrences of a variable
Task: Find all uses of user_name 1. Move cursor to user_name 2. * - Search for this word 3. n - Jump to next occurrence 4. n - Jump to next occurrence again
0.4 Basic Replace: The Simple Transformation
0.4.1 The Substitute Command Structure
0.4.2 Basic Replace Examples
Example 1: Replace in current line
Example 2: Replace in entire file
Example 3: Replace with confirmation
0.4.3 Practical Replace Examples
Example 1: Renaming a variable
Task: Change old_name to user_name 1. :%s/old_name/user_name/g - Replace all occurrences 2. Enter - Execute the command
Result:
Example 2: Updating function calls
Task: Change calculate_something to compute_value 1. :%s/calculate_something/compute_value/g 2. Enter
0.5 Advanced Search Patterns
0.5.1 Using Regular Expressions
Enable “very magic” mode for easier regex:
0.5.2 Common Regex Patterns
| Pattern | What It Matches | Example |
|---|---|---|
\w+ |
One or more word characters | hello, user123 |
\d+ |
One or more digits | 123, 42 |
\s+ |
One or more whitespace | spaces, tabs, newlines |
.* |
Any characters | anything |
^ |
Start of line | beginning |
$ |
End of line | end |
\< |
Start of word | word boundary |
\> |
End of word | word boundary |
0.5.3 Advanced Search Examples
Example 1: Finding function definitions
Example 2: Finding numbers
Example 3: Finding email addresses
0.6 Advanced Replace Patterns
0.6.1 Capture Groups and Backreferences
Use parentheses to capture parts of the match:
This swaps two words: John Doe becomes Doe, John
0.6.2 Advanced Replace Examples
Example 1: Swapping function parameters
Task: Swap parameters to (price, tax_rate)
Example 2: Adding quotes to values
Task: Add quotes around the values
Result:
Example 3: Converting camelCase to snake_case
Task: Convert to snake_case
Result:
0.7 Range Specifications
0.7.1 Different Ways to Specify Range
| Range | What It Means | Example |
|---|---|---|
% |
Entire file | :%s/old/new/g |
. |
Current line | :s/old/new/g |
1,5 |
Lines 1 to 5 | :1,5s/old/new/g |
.,+5 |
Current line + 5 lines | :.,+5s/old/new/g |
'a,'b |
From mark a to mark b | :'a,'bs/old/new/g |
/start/,/end/ |
From pattern to pattern | :/start/,/end/s/old/new/g |
0.7.2 Practical Range Examples
Example 1: Replace in a function
Task: Replace total with sum only in the function
Example 2: Replace in visual selection 1. V - Start line visual mode 2. Select the lines you want 3. : - Enter command mode (you’ll see :'<,'>) 4. s/old/new/g - Replace in selection
0.8 Flags and Options
0.8.1 Common Flags
| Flag | What It Does | Example |
|---|---|---|
g |
Global (all in line) | :s/old/new/g |
c |
Confirm each replacement | :s/old/new/gc |
i |
Ignore case | :s/old/new/gi |
I |
Don’t ignore case | :s/old/new/gI |
n |
Count matches only | :s/old/new/gn |
0.8.2 Confirmation Options
When using the c flag, you’ll see these options: - y - Yes, replace this match - n - No, skip this match - a - All, replace this and all remaining - q - Quit, stop replacing - l - Last, replace this match and quit
0.9 Practical Search and Replace Workflows
0.9.1 Workflow 1: Refactoring Variable Names
Scenario: You have a variable called data that should be user_data
Steps: 1. :%s/\<data\>/user_data/gc - Replace with confirmation 2. Review each replacement 3. Accept or reject each change
0.9.2 Workflow 2: Updating API Endpoints
Scenario: Change API version from v1 to v2
Steps: 1. :%s/v1/v2/g - Replace all v1 with v2 2. Check the results
0.9.3 Workflow 3: Format Consistency
Scenario: Ensure consistent string quotes
Steps: 1. :%s/'/"/g - Replace all single quotes with double quotes
0.10 Advanced Techniques
0.10.1 Using the Search History
| Command | What It Does |
|---|---|
/ then ↑ |
Previous search |
: then ↑ |
Previous command |
q/ |
Open search history window |
q: |
Open command history window |
0.10.2 Search and Replace with External Commands
This runs an external command for each match.
0.10.3 Multiple File Search and Replace
0.11 Common Patterns and Recipes
0.11.1 Pattern 1: Clean Up Whitespace
0.11.2 Pattern 2: Format Code
0.11.3 Pattern 3: Convert Data Formats
0.11.4 Pattern 4: Add/Remove Comments
0.12 Practice Exercise: Search and Replace Mastery
Create a file with this content:
def calculateTotal(itemList):
total_sum = 0
for current_item in itemList:
if current_item.price > 0:
total_sum = total_sum + current_item.price
else:
print('Invalid price for item')
return total_sum
def processOrder(orderData):
items = orderData.get('items')
total = calculateTotal(items)
return {'total': total, 'status': 'processed'}
# Test data
test_data = {
'items': [
{'name': 'laptop', 'price': 1000},
{'name': 'mouse', 'price': 25}
]
}Practice these operations:
- Basic replacements:
- Change
calculateTotaltocalculate_total - Change
itemListtoitems - Change
total_sumtototal
- Change
- Pattern-based replacements:
- Change all single quotes to double quotes
- Add spaces around
=operators - Convert camelCase to snake_case
- Advanced patterns:
- Swap function parameters
- Add type hints to functions
- Format dictionary consistently
- Confirmation practice:
- Use
cflag to confirm each replacement - Practice accepting/rejecting changes
- Use
0.13 Building Search and Replace Muscle Memory
0.13.1 Week 1: Basic Operations
- Practice basic search (
/,?,n,N) - Use simple replace (
:s/old/new/g) - Master file-wide replace (
:%s/old/new/g)
0.13.2 Week 2: Patterns and Ranges
- Learn basic regex patterns
- Practice range specifications
- Use confirmation flag (
c)
0.13.3 Week 3: Advanced Techniques
- Master capture groups and backreferences
- Practice complex pattern matching
- Use external commands
0.13.4 Week 4: Real-world Applications
- Apply to actual coding projects
- Develop personal pattern library
- Combine with other Vim operations
0.14 What’s Next?
You now master: - Basic search operations and navigation - Simple and advanced replace patterns - Regular expressions and capture groups - Range specifications and flags - Confirmation and review processes - Common patterns and workflows
In the next post, we’ll explore Registers and Macros and learn to automate repetitive tasks with incredible efficiency.
0.15 Key Takeaways
- Search first, replace second - always verify your pattern
- Use confirmation - the
cflag prevents mistakes - Master regex patterns - they unlock incredible power
- Practice with real code - build your pattern library
- Combine with other operations - search/replace integrates with everything
Search and replace in Vim transforms you from a manual editor to an automation wizard. Once you master these patterns, you’ll handle large-scale text transformations with confidence and precision.
Ready to automate repetitive tasks? Continue with Registers and Macros to master copy-paste on steroids and task automation.
Reuse
Citation
@online{2026,
author = {, Hasan},
title = {Search and {Replace} {Mastery:} {Find} and {Transform}
{Anything} {Instantly}},
date = {2026-08-23},
langid = {en}
}