Search and Replace
Searching with / and *, safe find-and-replace with :s and its flags, the Vim regex you actually need, and renaming across a project with :vimgrep and the quickfix list.
By The Dark DebuggerUpdated 20 min read
This article covers searching inside a file (/, ?, n, *), the substitute command :s with its flags and ranges, the parts of Vim's regular expressions you will actually use, repeating substitutions, and searching and replacing across many files with :vimgrep and the quickfix list. It assumes the editing commands from Editing Text and Operators, Motions, and Text Objects. Ranges are previewed here and covered fully in Ex Commands, Ranges, and :global.
Why "find and replace all" is not enough
You need to rename user_id to account_id in a billing module. Here it is:
def charge(user_id, amount):
if user_id in BLOCKED:
raise PermissionError(f"user {user_id} is blocked")
log.info("charging user_id=%s amount=%s", user_id, amount)
return gateway.charge(user_id=user_id, cents=int(amount * 100))
def is_admin(superuser_id, user_identity):
return superuser_id == user_identity.idA plain "replace all" (:%s/user_id/account_id/g) did this to the last three lines:
def is_admin(superaccount_id, account_identity):
return superaccount_id == account_identity.idsuperuser_id and user_identity contain user_id, so they were renamed too, and the code is now wrong in a way no test of charge() will catch. This article is about doing it right: matching whole words, counting matches before changing anything, confirming each change, and checking the result.
Searching: / and ?, n and N
/pattern and Enter searches forward; ?pattern searches backward. n repeats the search in the same direction and N in the opposite direction. The sample is a worker log:
2026-11-09 14:01:55 INFO worker-1 picked job 8812
2026-11-09 14:02:17 ERROR worker-1 job 8812 failed: timeout after 30s
2026-11-09 14:02:18 INFO worker-2 picked job 8813
2026-11-09 14:02:40 WARN worker-2 job 8813 slow: 12s
2026-11-09 14:03:02 ERROR worker-2 job 8814 failed: connection refused
2026-11-09 14:03:05 info worker-3 heartbeatStarting at the top:
| Keys | Cursor lands on |
|---|---|
/ERROR Enter | 2,21 |
n | 5,21 |
n | 2,21, with a message (below) |
N | 5,21 |
?INFO Enter | 3,21 |
n | 1,21 (n after ? keeps searching backward) |
When a search runs off the end of the file it wraps around and tells you so:
search hit BOTTOM, continuing at TOP 2,21 AllIf nothing matches:
E486: Pattern not found: FATAL 1,1 AllSearches are jumps, so Ctrl-O takes you back to where you started (see the jump list). And because / is a motion, it works after operators: d/ERROR deletes up to the next ERROR.
* and #: search for the word under the cursor
* searches forward for the word under the cursor, as a whole word; # does the same backward. In the billing module, with the cursor on user_id in line 1, * jumped to 2,8, and the command line showed the pattern it built:
/\<user_id\> 2,8 All\< and \> mean "start of word" and "end of word", so superuser_id and user_identity are skipped. Pressing n six more times visited 3,39, 4,24, 4,47, 5,27, 5,35, then wrapped to 1,12: seven matches, every real use of the variable.
g* and g# search for the same text without the word boundaries (the command line showed /user_id). That matches the longer names too.
incsearch, hlsearch, and case
Four options control how searching feels. With no vimrc, :set hlsearch? incsearch? ignorecase? smartcase? showed:
nohlsearch
incsearch
noignorecase
nosmartcaseincsearch(on, from Vim's defaults) moves the cursor to the first match as you type the pattern, so you can see whether it is right before pressingEnter.hlsearch(off by default in Vim; Neovim's documentation lists it as on by default) highlights every match of the last search. It stays on until the next search, so:nohlsearch(or:noh) clears the highlighting without turning the option off.ignorecasemakes searches case-insensitive, andsmartcaseturns case sensitivity back on whenever the pattern contains a capital letter.
I recommend set hlsearch ignorecase smartcase, which is in the starter vimrc from Installing Vim. The effect on the worker log, counting matches (the n flag, explained below):
| Settings | Command | Result |
|---|---|---|
| defaults | :%s/info//gn | 1 match on 1 line |
| defaults | :%s/info//gin (the i flag) | 3 matches on 3 lines |
ignorecase smartcase | :%s/info//gn | 3 matches on 3 lines |
ignorecase smartcase | :%s/Info//gn | E486: Pattern not found: Info |
ignorecase smartcase | :%s/info\C//gn | 1 match on 1 line |
\c anywhere in a pattern forces case-insensitive matching and \C forces case-sensitive matching, whatever the options say.
The substitute command
:[range]s/pattern/replacement/[flags]Without a range, :s works on the current line only. Without the g flag, it replaces only the first match on each line. On line 5 of the billing module:
return gateway.charge(user_id=user_id, cents=int(amount * 100)):s/user_id/account_id/ changed the first one only:
return gateway.charge(account_id=user_id, cents=int(amount * 100)):s/user_id/account_id/g changed both:
return gateway.charge(account_id=account_id, cents=int(amount * 100))% as the range means "every line in the file". So :%s/old/new/g is "replace everywhere", and that is the command that produced the superaccount_id mess at the top of this article.
The flags you need
| Flag | Meaning |
|---|---|
g | All matches on each line, not just the first |
c | Confirm each replacement |
i / I | Ignore case / match case for this command, whatever the options say |
n | Count the matches, change nothing |
e | No error if there are no matches (useful in scripts and with :cfdo) |
& | Keep the flags from the previous substitute (must come first) |
Count first, then replace
n makes :s report instead of change. It is the safest first step for any file-wide replacement:
:%s/user_id//gn11 matches on 7 lines:%s/\<user_id\>//gn7 matches on 5 linesEleven versus seven: four matches are inside other names. With the word boundaries, the replacement does exactly what you want:
:%s/\<user_id\>/account_id/g7 substitutions on 5 linesdef charge(account_id, amount):
if account_id in BLOCKED:
raise PermissionError(f"user {account_id} is blocked")
log.info("charging account_id=%s amount=%s", account_id, amount)
return gateway.charge(account_id=account_id, cents=int(amount * 100))
def is_admin(superuser_id, user_identity):
return superuser_id == user_identity.idLine 4 is worth a second look. The log message text user_id=%s was renamed too. That may be what you want (it keeps logs consistent), or it may break a log parser that expects the old key. Word boundaries cannot tell code from strings, so the next step matters.
Confirm each change with c
Add c and Vim stops at each match, highlights it, and asks:
replace with account_id (y/n/a/q/l/^E/^Y)? 1,12 All| Answer | Does |
|---|---|
y / n | Replace this one / skip it |
a | Replace this and all remaining matches |
q or Esc | Stop |
l | Replace this one, then stop ("last") |
| Ctrl-E / Ctrl-Y | Scroll the screen to see more context |
When I answered y, y, n, q, the first two matches (lines 1 and 2) were replaced, the f-string on line 3 was skipped, and the command stopped at line 4, leaving the rest unchanged. For a rename across code, gc and a few seconds of reading is cheap insurance.
Special characters in the replacement
| In the replacement | Inserts |
|---|---|
& | The whole match |
\1 to \9 | Capture groups 1 to 9 |
\r | A line break |
\u / \l | Uppercase / lowercase the next character |
\U / \L ... \E | Uppercase / lowercase until \E or the end |
\= expression | The result of a Vimscript expression |
& reuses the match. To bracket every job reference in the log, :%s/\<job \d\+/[&]/g:
2026-11-09 14:01:55 INFO worker-1 picked [job 8812]
2026-11-09 14:02:17 ERROR worker-1 [job 8812] failed: timeout after 30s
2026-11-09 14:02:18 INFO worker-2 picked [job 8813]
2026-11-09 14:02:40 WARN worker-2 [job 8813] slow: 12s
2026-11-09 14:03:02 ERROR worker-2 [job 8814] failed: connection refused
2026-11-09 14:03:05 info worker-3 heartbeatAnd :%s/\<info\>/\U&/ fixed the lowercase level on the last line to INFO.
Ranges, briefly
The range in front of :s picks the lines:
| Range | Lines |
|---|---|
| (none) | Current line |
% | Whole file |
5,12 | Lines 5 to 12 |
.,$ or ,$ | Current line to the end |
.,+3 | Current line and the next three |
'<,'> | The last Visual selection (Vim inserts it when you press : in Visual mode) |
For example, 2G then :,$s/.../.../ skips a CSV header row, as in the expression example below. Pattern ranges like /start/,/end/ and the :global command, which runs :s only on lines matching another pattern, are covered in Ex Commands, Ranges, and :global.
Vim regex essentials
Vim's regular expressions look like other regex flavors with one twist: by default (called magic mode), many special characters need a backslash. ., *, ^, $ and [...] work as usual, but +, ?, |, (, ) and { are literal unless escaped.
| Meaning | Default (magic) | Very magic (\v) | PCRE / grep -E |
|---|---|---|---|
| one or more | \+ | + | + |
| zero or one | \= or \? | = or ? | ? |
| n to m times | \{2,4} | {2,4} | {2,4} |
| as few as possible | \{-} | {-} | *? |
| group | \(...\) | (...) | (...) |
| word boundary | \< \> | < > | \b |
| digit, word char, space | \d \w \s | same | same |
| set match start / end | \zs / \ze | same | lookbehind / lookahead |
Alternation ("this or that") is \| in magic mode, as in /ERROR\|WARN, and a plain | in very magic mode. Start a pattern with \v ("very magic") and every punctuation character becomes special, which reads much more like the regex in other languages.
Groups and \1: reformatting dates in a CSV
A payments export uses US dates, and the importer wants ISO 8601 (YYYY-MM-DD):
id,customer,date,amount
1001,acme-corp,11/02/2026,129.00
1002,globex,11/03/2026,75.50
1003,initech,10/28/2026,310.25
1004,umbrella,9/30/2026,42.00In default magic syntax every group and count needs a backslash, and the slashes in the data must be escaped because / is the delimiter:
:%s/\(\d\{1,2}\)\/\(\d\{1,2}\)\/\(\d\{4}\)/\3-\1-\2/The same command in very magic is easier to read:
:%s/\v(\d{1,2})\/(\d{1,2})\/(\d{4})/\3-\1-\2/Both produced the same result:
id,customer,date,amount
1001,acme-corp,2026-11-02,129.00
1002,globex,2026-11-03,75.50
1003,initech,2026-10-28,310.25
1004,umbrella,2026-9-30,42.00Look at the last row: 2026-9-30 is not valid ISO 8601, because the month in 9/30/2026 had one digit. Regex groups can reorder text but cannot pad it. An expression can:
:%s#\v<(\d{1,2})/(\d{1,2})/(\d{4})>#\=printf("%s-%02d-%02d", submatch(3), submatch(1), submatch(2))#4 substitutions on 4 linesid,customer,date,amount
1001,acme-corp,2026-11-02,129.00
1002,globex,2026-11-03,75.50
1003,initech,2026-10-28,310.25
1004,umbrella,2026-09-30,42.00Three things changed. # is the delimiter, so the slashes in the pattern need no escaping (any single-byte non-alphanumeric character works as a delimiter). < and > (very magic word boundaries) stop the pattern from matching inside longer numbers. And \= makes the replacement a Vimscript expression, where submatch(N) is group N and printf pads with zeros.
\zs: replace only part of the match
\zs marks where the match really starts; everything before it must be present but is not replaced. In an nginx config:
server {
access_log /var/log/nginx/app.access.log;
error_log /var/log/nginx/app.error.log warn;
}:%s/\/var\/log\/nginx\/\zsapp/orders/g renamed only the file names in that directory:
server {
access_log /var/log/nginx/orders.access.log;
error_log /var/log/nginx/orders.error.log warn;
}= for computed replacements
An expression replacement can do arithmetic. Adding 20% VAT to the amounts in the payments file, skipping the header (2G, then):
:,$s/\d\+\.\d\+$/\=printf("%.2f", str2float(submatch(0)) * 1.2)/id,customer,date,amount
1001,acme-corp,11/02/2026,154.80
1002,globex,11/03/2026,90.60
1003,initech,10/28/2026,372.30
1004,umbrella,9/30/2026,50.40submatch(0) is the whole match. For anything more involved, a real script is clearer, but for a one-off fix in a file you already have open, this saves a round trip.
Repeating a substitution: &, :&& and g&
| Command | Repeats the last :s | Flags |
|---|---|---|
& | on the current line | dropped |
:&& | on the current line (or a given range) | kept |
g& | on every line | kept |
On the worker log, 2G then :s/worker/w/, then 3G:&& and 4G&:
2026-11-09 14:01:55 INFO worker-1 picked job 8812
2026-11-09 14:02:17 ERROR w-1 job 8812 failed: timeout after 30s
2026-11-09 14:02:18 INFO w-2 picked job 8813
2026-11-09 14:02:40 WARN w-2 job 8813 slow: 12s
2026-11-09 14:03:02 ERROR worker-2 job 8814 failed: connection refused
2026-11-09 14:03:05 info worker-3 heartbeatg& is the "I tested it on one line, now do it everywhere" command. After :s/ \+/ /g squeezed the double space after INFO on line 1, g& applied the same substitution, g flag included, to the whole file.
An empty pattern means "the last search pattern". After * or /, :%s//account_id/g replaces whatever you just searched for, so you can build the pattern interactively with incsearch and then substitute without retyping it. After g* on user_id, :%s///gn reported 11 matches on 7 lines.
Searching across files: :vimgrep and the quickfix list
A real rename spans files. This small project has three Python files:
./api/handlers.py
./billing/charge.py
./billing/refund.pyFrom the project root, start Vim and search all of them:
:vimgrep /\<user_id\>/gj **/*.py**/*.py matches Python files in all subdirectories, g records every match on a line (not just the first), and j stops Vim from jumping to the first match. The results go into the quickfix list. :clist prints it:
:clist
1 api/handlers.py:5 col 5-12: user_id = request.json["user_id"]
2 api/handlers.py:5 col 29-36: user_id = request.json["user_id"]
3 api/handlers.py:6 col 19-26: return charge(user_id, request.json["amount"])
4 billing/charge.py:1 col 12-19: def charge(user_id, amount):
5 billing/charge.py:2 col 27-34: return gateway.charge(user_id=user_id, cents=int(amount * 100))
6 billing/charge.py:2 col 35-42: return gateway.charge(user_id=user_id, cents=int(amount * 100))
7 billing/refund.py:1 col 12-19: def refund(user_id, charge_id):
8 billing/refund.py:2 col 25-32: audit.log("refund", user_id=user_id, charge=charge_id)
9 billing/refund.py:2 col 33-40: audit.log("refund", user_id=user_id, charge=charge_id)
Press ENTER or type command to continue| Command | Does |
|---|---|
:copen / :cclose | Open / close the quickfix window (press Enter on an entry to jump there) |
:cnext / :cprev | Go to the next / previous match, opening files as needed |
:cfirst / :clast | First / last match |
:cdo cmd | Run cmd at every entry |
:cfdo cmd | Run cmd once in every file that has an entry |
:cnext from the first entry opened api/handlers.py at the second match and reported (2 of 9). To apply the rename to every file and save each one:
:cfdo %s/\<user_id\>/account_id/ge | updatee avoids errors in files with no match, and update writes the file only if it changed. Vim reported each file as it went (trimmed to the write messages):
[…]
"api/handlers.py" 10L, 224B written
[…]
"billing/charge.py" 2L, 106B written
[…]
"billing/refund.py" 3L, 137B writtenBack in the shell, always check the result of a multi-file replacement:
grep -rn 'account_id\|user_id' --include=*.py . | sort./api/handlers.py:10: return superuser_id in ADMINS
./api/handlers.py:5: account_id = request.json["account_id"]
./api/handlers.py:6: return charge(account_id, request.json["amount"])
./api/handlers.py:9:def is_admin(superuser_id):
./billing/charge.py:1:def charge(account_id, amount):
./billing/charge.py:2: return gateway.charge(account_id=account_id, cents=int(amount * 100))
./billing/refund.py:1:def refund(account_id, charge_id):
./billing/refund.py:2: audit.log("refund", account_id=account_id, charge=charge_id)superuser_id survived, as intended. But look at line 5 of handlers.py: request.json["account_id"]. The JSON key that API clients send was renamed too. Every client still sending user_id will now get a KeyError. The quickfix list showed this in entry 2 before anything changed. That is why, for anything touching an interface, I run the substitution once per quickfix entry and confirm each one:
:cdo s/\<user_id\>/account_id/c | update:cdo visits each of the 9 entries and runs :s there. Without g, each run replaces the first remaining match on that line, so two entries on the same line are handled one after the other. I answered n at entry 2, the JSON key, and y everywhere else. The result:
./api/handlers.py:5: account_id = request.json["user_id"]and every other line as before. One trap I hit while testing: :vimgrep does not set the last search pattern, so :cdo s//account_id/c (empty pattern) failed with E35: No previous regular expression. Spell the pattern out.
If nothing matches, :vimgrep says so:
E480: No match: customer_id 0,0-1 All:vimgrep uses Vim's own regex engine and reads every file into Vim, which is fine for a project and slow for a huge tree. :grep runs an external program (grep -n by default, controlled by the grepprg option) and fills the same quickfix list, so all the :c commands work on its results too.
Where you'll use this
Safe variable rename, start to finish:
*on the variable, thenna few times to see how it is used.:%s///gnto count (the empty pattern reuses the*pattern with its\<\>).:%s//new_name/gcand answer each prompt; skip matches in strings and external interfaces.- Check the leftovers with
/\<old_name\>(E486means none are left) orgrep -nin a shell.
Data cleanup before an import: reformatting dates, normalizing case (\U&), trimming whitespace (:%s/\s\+$//e), or adding a column with \=. All of these are quicker to do in Vim and check by eye than to write a script for, when the file is a one-off.
Config migrations: changing paths with a # delimiter, swapping hostnames across an inventory, or moving log files with \zs. For changes across a repository, :vimgrep or :grep into the quickfix list, review with :copen, then :cdo or :cfdo with | update.
Common mistakes
Writing + as in other regex flavors. In Vim's default magic mode, + is a literal plus sign:
:%s/\d+s/N/gE486: Pattern not found: \d+sUse \+, or start the pattern with \v. :%s/\d\+s\>/Ns/g replaced 30s and 12s as intended.
Slashes in the pattern. Paths are full of /, which ends the pattern early:
:%s//var/log/nginx//srv/logs/nginx/gE488: Trailing characters: og/nginx//srv/logs/nginx/gVim read the empty pattern (the last search), the replacement var, and l as a flag, then choked on the rest. Pick another delimiter: :%s#/var/log/nginx#/srv/logs/nginx#g worked.
Using \n to insert a line break. In the pattern, \n matches a line break. In the replacement, \n inserts a NUL byte. To split a comma-separated host list onto separate lines:
ALLOWED_HOSTS=api.example.com, admin.example.com, localhost:s/, /\n/g produced one line with NUL characters, which cat -A shows as ^@:
ALLOWED_HOSTS=api.example.com^@admin.example.com^@localhost$:s/, /\r/g produced the three lines that were wanted:
ALLOWED_HOSTS=api.example.com$
admin.example.com$
localhost$Replacing a substring when you meant a word. The superaccount_id result at the top of this article. Use * or \<...\>, and count with the n flag before replacing.
Trusting a multi-file replace without reviewing it. As the JSON-key example showed, word boundaries cannot tell an internal variable from an external contract. Read the quickfix list before running :cfdo, and diff or grep afterwards.
Summary
/and?search forward and backward;nrepeats in the same direction,Nin the opposite one. Searches wrap around the file and are jumps (Ctrl-O returns).*and#search for the word under the cursor with\<\>boundaries;g*andg#drop the boundaries.incsearchpreviews matches as you type (on by default in Vim),hlsearchhighlights all matches (off by default;:nohclears it), andignorecaseplussmartcasegive case-insensitive search unless you type a capital.\cand\Coverride per pattern.:s/pat/rep/changes the first match on the current line;%makes it file-wide,gall matches per line,cconfirms each one,nonly counts,esuppresses "not found".- Magic mode needs
\+,\?,\(...\),\{n,m}and\|;\vmakes them plain.\<\>are word boundaries,\zs/\zetrim the match,&and\1reuse matched text, and\=computes the replacement. - Use a different delimiter (
#) for paths, and\r, not\n, to insert a line break. &repeats the last substitute on this line,g&on every line with the same flags; an empty pattern reuses the last search.:vimgrep /pat/gj **/*.extfills the quickfix list. Review it with:clistor:copen, then apply changes with:cdoor:cfdo ... | update.
Exercises
The files are the ones used above: worker.log, site.conf, billing.py and payments.csv.
How many ERROR lines does worker.log contain? Answer from inside Vim without modifying the file.
Show Solution
:%s/ERROR//gn2 matches on 2 linesThe n flag reports the count and makes no change, even though the replacement is empty.
In site.conf, change every /var/log/nginx to /srv/logs/nginx without escaping any slashes.
Show Solution
:%s#/var/log/nginx#/srv/logs/nginx#gserver {
access_log /srv/logs/nginx/app.access.log;
error_log /srv/logs/nginx/app.error.log warn;
}Any single-byte character other than a letter, digit, \, " or | can be the delimiter. #, , and + are common choices.
In billing.py, rename user_id to account_id without touching superuser_id or user_identity. Count first, then replace.
Show Solution
:%s/\<user_id\>//gn7 matches on 5 lines:%s/\<user_id\>/account_id/g7 substitutions on 5 linesThe is_admin function is unchanged. An alternative that saves typing the pattern: put the cursor on user_id, press *, then run :%s//account_id/g.
Convert every M/D/YYYY or MM/DD/YYYY date in payments.csv to YYYY-MM-DD, so that 9/30/2026 becomes 2026-09-30.
Hint
Groups can reorder the parts but cannot add a leading zero. \= with printf can.
Show Solution
:%s#\v<(\d{1,2})/(\d{1,2})/(\d{4})>#\=printf("%s-%02d-%02d", submatch(3), submatch(1), submatch(2))#id,customer,date,amount
1001,acme-corp,2026-11-02,129.00
1002,globex,2026-11-03,75.50
1003,initech,2026-10-28,310.25
1004,umbrella,2026-09-30,42.00%02d pads the month and day to two digits.
The log has durations like 30s and 12s. Rewrite each one as milliseconds (30000ms, 12000ms) with a single substitute command, without touching job numbers or timestamps.
Show Solution
:%s/\v(\d+)s>/\=submatch(1) * 1000 . "ms"/g2026-11-09 14:01:55 INFO worker-1 picked job 8812
2026-11-09 14:02:17 ERROR worker-1 job 8812 failed: timeout after 30000ms
2026-11-09 14:02:18 INFO worker-2 picked job 8813
2026-11-09 14:02:40 WARN worker-2 job 8813 slow: 12000ms
2026-11-09 14:03:02 ERROR worker-2 job 8814 failed: connection refused
2026-11-09 14:03:05 info worker-3 heartbeats> requires the s to end a word, so 8812 (no s) and the timestamps are not matched. In the expression, * multiplies and . joins strings.
Tested with: Vim 9.1.0016 and GNU grep 3.11 on Ubuntu 24.04 (WSL2), November 2026, with Vim's stock defaults.vim and no personal vimrc.
Every command was typed into a real Vim session and every result is the saved file or the screen line Vim printed. The confirm-dialog answers (y, y, n, q) and the :cfdo run were done exactly as described. The Neovim hlsearch default is taken from Neovim's documentation; Neovim was not installed.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Vim tutorial here is tested end to end before publishing.