A while back I asked Claude Code to "tidy up three spots in this function." The first Edit went through cleanly. The second failed with String to replace not found in file, and the third tripped on Found 2 matches of the string to replace, but replace_all is false. I sat there with my hands off the keyboard, because the text had been there a few seconds earlier.
If you use Claude Code every day, you will meet this sooner or later. Most of my work — SwiftUI refactors, MDX swaps, the occasional throwaway tool — is delegated to it, so I have met it more often than I'd like to admit. It looks fiddly, but the cause narrows to three patterns, the messages sort into five shapes, and the rescue is close to mechanical once you know which one you are in.
This piece is for you if an Edit on the same file keeps failing from the second attempt on, and you're not sure which fix to reach for. By the end, the first line of the error should be enough to tell you the next move.
What's actually happening — one turn, one snapshot
The thing worth internalising first: when several Edits are issued in a single turn, their old_string values are all built from the same view of the file.
As far as I can observe, the sequence looks like this:
- Claude reads the file once with
Read. - From that snapshot, it generates
old_stringfor Edits 1, 2 and 3 together. - Edit 1 applies, and the targeted text on disk becomes its
new_string. - Edit 2's
old_stringis still based on the Read snapshot. - If Edit 1 removed what Edit 2 was looking for, the string simply isn't there (
not found). - If Edit 1's
new_stringadded another copy of the pattern, Edit 2 now matches in several places (Found N matches).
Edits are applied serially, but their old_string values were minted against the same older picture. When Claude works one Edit at a time and looks at each result before the next, the cascade rarely happens. What triggers it is the "do it all at once" way of asking.
Triage table for the error messages
These are the messages as recorded in public issues as of November 2026. Wording can drift slightly between versions, so match on the first few words rather than the whole line.
| Message (start) | Likely cause | How to check | Fix |
|---|---|---|---|
String to replace not found in file | An earlier Edit rewrote that spot, or tabs/spaces differ | Run the counting script below; look at whitespace with cat -A | Insert a Read, then Edit only what remains |
Found 2 matches of the string to replace, but replace_all is false | An earlier new_string copied the pattern, or the line already repeats | Print the count and line numbers with the script | Widen old_string with surrounding lines; use replace_all only if every copy should change |
File has been modified since read, either by the user or by a linter | A formatter, hook or your editor rewrote the file after the Read | Look for formatter hooks in /hooks; suspect editor autosave | Re-read, and keep formatters from running between Edits |
File has been unexpectedly modified | An IDE extension or file watcher re-saved the file (sometimes only the mtime changes) | Close the file in your editor and retry | Pause editor-side format-on-save while Claude works |
File has not been read yet. Read it first before writing to it | The file was never read, or the read record dropped in a long session | Check whether a Read precedes the Edit | Ask Claude to Read that file first |
The third message appears when something changes the file between the Read and the Edit. There is a GitHub issue pointing out that the wording doesn't always match what happened, and if the formatter keeps rewriting the file, re-reading can loop.
Count the matches first
An error message alone doesn't tell you what the file looks like right now. So before I ask Claude to retry, I count how many times the old_string appears. It uses the := operator, so it needs Python 3.8 or later.
#!/usr/bin/env python3
"""Show how many times old_string appears in a file, and on which lines."""
import sys
from pathlib import Path
path, needle = sys.argv[1], sys.argv[2]
text = Path(path).read_text(encoding="utf-8")
count = text.count(needle)
if count == 0:
print("0 matches: this will be 'not found' (removed by an earlier Edit, or whitespace differs)")
# Retry ignoring whitespace, to expose look-alike strings that don't match
squash = lambda s: "".join(s.split()).replace(" ", "")
if squash(needle) in squash(text):
print(" Matches if whitespace is ignored: suspect tabs, spaces or a full-width space")
elif count == 1:
print("1 match: unique, safe to Edit")
else:
print(f"{count} matches: this will be 'Found {count} matches'")
start = 0
while (idx := text.find(needle, start)) != -1:
line = text.count("\n", 0, idx) + 1
print(f" - line {line}")
start = idx + len(needle)Run it like python3 count_match.py ContentView.swift '.padding(.top, 16)'. The output looks like this:
2 matches: this will be 'Found 2 matches'
- line 41
- line 58
Zero means "gone," two or more means "multiplied," and that tells you which fix to reach for. If it reports zero but says it matches with whitespace ignored, you are looking at tabs versus spaces or a stray full-width space. Until I settled on this, I used to guess from the error and fix the wrong thing, then fall into the same hole again.
Case 1: Edit 1 deletes what Edit 2 is looking for
The most common shape. Picture a SwiftUI view with three near-identical modifier chains. Claude plans to delete one .padding(.top, 16) and rewrite another to .padding(.top, 24). By the time Edit 2 fires, the literal string it wanted is gone.
Error: String to replace not found in file.
String: .padding(.top, 16)
I hit this constantly in AdMob-related SwiftUI work, where helper-function call sites cluster together and Claude tries to "delete the upper one and rewrite the lower one" in one sweep.
Fix: tell Claude to slip a Read in
Reply with one line: "Please Read the file again and run only the remaining Edits." Claude refreshes its view and regenerates old_string for whatever is left.
To avoid the cascade up front, change how you ask:
- Risky framing: "Make all three edits in one go."
- Safe framing: "Apply the edits one at a time, top to bottom. After each Edit,
Readthe file and verify the result before moving on."
The second is slower. For structural refactors it still finishes sooner overall.
Case 2: Edit 1's new_string multiplies the pattern
The other shape: Edit 1 inserts text that contains the very pattern Edit 2 wants to match.
Error: Found 2 matches of the string to replace, but replace_all is false.
String: const handleSubmit = async () =>
For example: "Split the body of const handleSubmit = async () => and have it call an internal helper of the same shape." If the helper side keeps the same signature, there are now two matches where there used to be one.
Fix: widen old_string until it's unique
Ask Claude to "regenerate old_string including the 3–5 lines around the target, then retry." Edit matching is exact, not fuzzy, so a wider window disambiguates. Check with the script above that it now reports one match.
Side by side, the difference is small but decisive:
// Before: the same line exists twice, so the target is ambiguous
const handleSubmit = async () =>
// After: include the line above and below to pin it to one place
export function CheckoutForm() {
const handleSubmit = async () => {
await submitOrder(cart);I keep a rule in CLAUDE.md: include the closing brace when editing the last function in a file, and include neighbouring import lines when editing imports. That alone lowered my multiple-match rate noticeably.
# Excerpt from CLAUDE.md
When using the Edit tool, make sure `old_string` is unique by including
a few surrounding lines. Especially for import statements, return blocks,
and empty braces, uniqueness is the top priority.Case 3: a formatter changed the file between Edits
Less frequent, and the hardest to see. If a PostToolUse hook runs a formatter, the indentation can normalise the moment Edit 1 lands, and the file no longer looks the way Claude last read it.
What you get here is not not found but File has been modified since read, either by the user or by a linter. If you read it as an old_string problem you will chase the wrong thing for a long time. When I had SwiftFormat wired to every Edit, I lost half a day before I noticed the message was different. Looking back, reading the first line of the error out loud would probably have saved me most of it.
Fix: don't run the formatter mid-cascade
My current setup runs the formatter only after the batch settles, on Stop instead of PostToolUse. The official hooks reference shows the structure: each event holds an array of groups, and each group has its own hooks array.
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "swiftformat ."
}
]
}
]
}
}Stop doesn't take a matcher, so leave matcher out (it would be ignored). Use SubagentStop if you want it to run when a subagent finishes. If you really want per-Edit formatting, remove the PostToolUse hook for the length of the refactor and confirm the state with /hooks. For the bigger picture on hooks, see the hooks guide.
Three ways to fix a multiple match — widen, replace_all, or sed
When you get a multiple-match error, there are three ways out, and they carry very different risks of touching lines you didn't mean to.
| Approach | Good for | Risky when | How to verify |
|---|---|---|---|
Widen old_string | You want to change exactly one spot | The surrounding code repeats too, so widening doesn't make it unique | The counting script reports 1 |
Edit with replace_all: true | Every copy in one file should change the same way | The same text also lives in comments or string literals | Read every line of git diff |
Bash + sed -i | Mechanical replacement across several files | The term has regex metacharacters, or you'll Edit the same file right after | Compare grep -rn before and after |
The rule fits in one line: one spot, widen; one whole file, replace_all; many files, sed. If you rewrite a file with sed and then Edit it, you'll land in "modified since read," so have Claude re-read that file before continuing.
Three common misreadings
"Re-reading always fixes it." Not while a formatter or IDE keeps rewriting the file — it changes again just before the next Edit. Stop the source of the rewrites first.
"replace_all is the safe default." It replaces every match, including the ones in comments or test fixtures. After any replace_all, I read the git diff line by line.
"The model is having a bad day." Most cascades come from packing several Edits into one turn. Splitting the request one Edit at a time is faster than switching models.
Triage flow — the order I actually run through
- Sort the error into one of the five shapes in the table above.
- For
not found, check whether the previous Edit touched the same region. - For
Found N matches, look at whether the recentnew_stringcopied the pattern. - For
modified since readorunexpectedly modified, check/hooksand your editor's autosave. - Once the cause is clear, tell Claude: "Re-Read the file, then apply the remaining Edits."
Steps 2 and 3 split most cases. The same error is covered from another angle in the article on old_string that won't become unique.
Prevention — splits that don't cascade
Cap Edits at three per file per turn. If a change needs more, ask Claude to handle one file at a time, with a Read after each.
Separate structural Edits from body Edits. Changing a signature and rewriting its body in the same turn invites the cascade. Do the signature first, confirm, then the body.
Push wide replacements down to Bash + sed. Renaming a symbol across ten or more sites is what sed -i 's/old/new/g' is for. A CLAUDE.md note — "four or more identical replacements: use sed" — lets Claude pick the right tool.
The next snag — "it succeeded, but the wrong line changed"
Once the errors stop, the next thing that bites is a successful Edit that changed the wrong place: a widened old_string that matched the neighbouring look-alike function, or a replace_all that also rewrote a comment.
After every batch of Edits, I check the diff with two lines:
git diff --stat # are the files and line counts what I expected?
git diff -U1 -- path/to/File.swift # just the changed lines, tightlyIf --stat shows a file I didn't expect, I stop there. If your verification output tends to run long, the piece on keeping hook output quiet on success is a useful companion; trimming what hooks return makes it easier for Claude not to miss the point of a diff.
Next step
When you hit this in real time, say "Re-Read the file, then continue." In my own work that clears most cases. The rest need the match count and a wider old_string, or a paused formatter.
The cascade isn't a broken tool; it comes from asking for everything at once — so decide your check-in size before you start.
I still turn back at the edge of this trap most weeks. Knowing how it works has shortened the stalls by a wide margin. If you've been losing flow to the same error, I hope this gives a little time back. Thanks for reading.