One evening I had Claude Code applying the same routine change across several repositories, and I stepped away. When I came back, the screen was full of retries. Edit would get rejected, Claude would reshape old_string slightly, try again, and get rejected again — each round quietly spending tokens.
My first reaction was that the tool was being too strict. After tracing the failures one by one, though, it turned out that almost none of them were about Claude's skill. Either I was giving it too little to anchor on, or the file on disk wasn't what I assumed it was.
What I'd like to say up front is that Edit fails in two different ways. In one, the string matches in more than one place and the tool can't choose. In the other, it matches nowhere. Before either of those, there are two gates that stop an edit on its preconditions: the file changed after it was read, or it hasn't been read at all. The exact error wording changes between Claude Code versions, so I stopped reading the message for its text and started asking which side of the split I was on.
Telling the two apart: "too many" or "none"
Edit looks for old_string in the file and replaces the single match with new_string. The comparison is exact — one space or one line-ending character off, and it's a different string.
| Symptom | What it means | Suspect first |
|---|---|---|
| Matched in several places | The snippet is too short to identify one spot | Context around old_string |
| No match found | What Claude remembers differs from what's on disk | Formatters, line endings, invisible characters, placeholders |
The first is a "not enough string" problem; the second is a "wrong string" problem. The fixes pull in opposite directions, so mixing them up sends you off adding context where you should be re-reading the file.
Working backwards from the English error text
Since what you actually see is a line of English, here's a table keyed on that. These are the messages reported as of November 2026 in my sessions and on GitHub issues; small details shift between versions.
| Message on screen (gist) | Likely causes | How to check | Fix |
|---|---|---|---|
Found 2 matches of the string to replace, but replace_all is false. | old_string is too short and occurs more than once | Count with grep -n "string" file | Add 1–2 lines of context; use replace_all: true only when you truly want every match |
String to replace not found in file. | Indentation, line endings, invisible characters, a placeholder, or a stray line-number prefix | Look at whitespace and line endings with cat -A and file | Re-read, then copy a substring that exists verbatim |
File has been modified since read, either by the user or by a linter. | A formatter, editor or other process rewrote the file after Read | Check format-on-save, hooks and file watchers | Read again, then Edit; reconsider where formatting runs |
File has not been read yet. Read it first before writing to it. | The file hasn't been read in this conversation (there are reports of the record vanishing after compaction) | Is there a Read of that file in the recent exchange? | Insert one Read |
The top two rows are the real either/or. The bottom two are gates that a re-read opens. If you start reshaping old_string while stuck at one of those, nothing changes except the retry count.
Multiple matches, fix 1: widen the block until it is unique
The most dependable move is to include lines above and below so the block occurs exactly once. Say setLoading(false) appears in two places.
// The block you want to change
if (response.ok) {
setData(await response.json());
setLoading(false);
}
// A look-alike elsewhere
if (cached) {
setData(cached);
setLoading(false);
}Passing setLoading(false) alone matches both. Pass the whole block, from the condition to the closing brace.
// old_string (now unique)
if (response.ok) {
setData(await response.json());
setLoading(false);
}
// new_string
if (response.ok) {
setData(await response.json());
setLastFetched(Date.now());
setLoading(false);
}Unless the file repeats the same structure over and over, that matches once. To make Claude do this by default, add one line to CLAUDE.md: "When using Edit, include 1–2 lines of surrounding context so old_string is unique." In my setup, retries dropped noticeably after that.
Multiple matches, fix 2: replace_all is only for "change every one"
Sometimes you genuinely want every occurrence changed — renaming a variable, migrating an import path. That's what replace_all: true is for, and I say so explicitly in the prompt.
Rename every occurrence of oldVarName to newVarName in this file.
Use replace_all: true so it happens in a single Edit call.The catch is that replace_all also rewrites accidental matches, such as a // TODO: fix oldVarName comment or the same spelling inside a string literal. I only use it for tokens unlikely to collide, like variable names, and not for ordinary words. Running grep -n first takes ten seconds and tells you whether "every one" is really what you mean.
Multiple matches, fix 3: split the work when blocks differ
When several similar blocks each need a different change, don't try to do it in one clever call. Asking Claude to "use a regex" doesn't help either, because Edit only accepts exact strings.
This is the order I now use in the prompt:
- Have Claude
Readthe whole file and count how many targets there are - Label them "Block A", "Block B" and so on, and build an
old_stringwith enough context for each - Apply them one at a time, and stop to investigate if any fails
Asking for that change plan first cut my rework by a good margin. My CLAUDE.md says: "For multi-location changes, present a bulleted change plan first, then run Edit in order."
Multiple matches, fix 4: when the structure changes, use Write
If a change touches roughly a third of a file or more, rewriting it with Write is faster and less error-prone than chaining Edit calls. Edit is built for local changes; adding, removing or reordering functions fights its assumptions.
A rough guide:
- A net change of about ±10 lines →
Editis fine - Replacing one whole function →
Editworks if the entire function is theold_string - Restructuring the file → switch to
Write
For an existing file you need to Read it before Write. Claude Code stops the write otherwise, and I'm glad of that — it keeps you from overwriting contents nobody has looked at.
"No match" is usually the file having changed
Now the second failure: the string Claude saw isn't on disk. The causes fall into three buckets.
- Something outside Claude rewrote the file after it was read
- Claude shortened its quote and produced a string that never existed
- There are characters on disk you can't see on screen
Case 1: format-on-save changed the indentation
This is the most common. editor.formatOnSave in VS Code, Prettier, ESLint's --fix, Black, gofmt — anything that rewrites the file on save can pull it out from under Claude.
Suppose Claude reads this:
function calculateTotal(items: Item[]) {
return items.reduce((sum, item) => sum + item.price, 0);
}Then a save lets Prettier turn four-space indentation into two:
function calculateTotal(items: Item[]) {
return items.reduce((sum, item) => sum + item.price, 0);
}Claude looks for the four-space line it remembers, and it isn't there any more.
I used to believe Claude had no way of noticing the file had changed. That was wrong. Claude Code tracks writes that happen after a Read, and when it catches one it stops earlier with a different message: File has been modified since read. The not found error is what you get when that check is slipped and Claude builds old_string from a stale memory. Either way the cause is the same — editing against an outdated copy — and so is the fix.
The lightest fix is to ask for a fresh read:
The file may have been reformatted on save.
Call Read again to get the current contents before editing.One sentence and Claude restarts from Read. For repositories I'll live in for a while, though, the real remedy is deciding when formatting runs and who triggers it.
Choosing where formatting lives
You don't have to give up formatting. You move it to a point where it can't collide with Claude's edits.
| Where it runs | When | Collisions with Edit | Good for |
|---|---|---|---|
| Editor format-on-save | When a person saves in the editor | Common — a human save lands between Claude's Read and Edit | Hours when you're writing without Claude |
| Claude Code PostToolUse hook | Right after each Edit / Write | Rare — the change always happens at the same, predictable point | Pairing with Claude while keeping code formatted |
| git pre-commit hook | At commit time | Almost never | When nothing should touch files mid-session |
If you're unsure: PostToolUse while pairing with Claude, pre-commit the rest of the time. The official hooks guide includes an example that runs Prettier after Edit and Write. In .claude/settings.json it looks like this (assuming jq and Prettier are installed):
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
]
}
}Because the hook fires immediately after Claude's own edit, the moment the file changes is pinned to the same spot every time. You lose the kind of failure where your hand and Claude's happen to cross. That said, issues still report modified since read after a formatter hook (for example #51361). A re-read gets past it, so I'd try one Read before deciding the hook is the problem.
Case 2: tabs and spaces look identical
If your editor renders a tab as four columns, you can't tell it from four spaces. The file has tabs, you assume spaces, you write your prompt that way, and Claude inherits the assumption.
cat -A settles it:
$ cat -A src/utils.ts | head -3
function calculate() {$
^Ireturn 42;$
}$^I is a tab and $ is the end of the line. If the file mixes both, telling Claude "this file indents with tabs" is often enough for the next Edit to go through.
For a repository you'll keep using, an .editorconfig lets editors and formatters agree on the rules:
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = trueI haven't verified whether Claude reads this file by itself. What I'm confident about is that the tools around it keep the files consistent, which is the part that helps.
Case 3: mixed CRLF and LF line endings
Code from Windows collaborators, or a repository with drifting git settings, can end up with some lines ending in \r\n and others in \n. A multi-line old_string that crosses those lines may stop matching.
Check with file:
$ file src/components/Button.tsx
src/components/Button.tsx: ASCII text, with CRLF line terminatorsTo standardize the whole repository on LF, add a .gitattributes at the root:
* text=auto eol=lf
Then renormalize — after committing or stashing any uncommitted work:
git add --renormalize .
git statusI used to run git rm --cached -r . followed by git reset --hard. But reset --hard throws away uncommitted changes, and my stomach dropped the one time it nearly did. Now I use --renormalize, read the diff, and commit only if it looks right.
For individual files, dos2unix is enough:
dos2unix src/components/*.tsxCase 4: invisible characters (zero-width spaces, BOM)
Rarer, but worth checking when the first three don't fit. Code pasted from web pages or passed through Markdown can pick up zero-width spaces (U+200B), non-breaking spaces (U+00A0), or a BOM (U+FEFF) at the start of the file.
# Look for invisible characters
grep -nP "[\x{00A0}\x{200B}-\x{200D}\x{FEFF}]" src/utils.tsIf you find any, remove them with sed:
sed -i 's/\xc2\xa0/ /g; s/\xe2\x80\x8b//g' src/utils.ts
sed -i '1s/^\xEF\xBB\xBF//' src/utils.tsThe stock macOS sed wants sed -i '' instead. Whenever I bring in a file from outside, I run file on it once to see the BOM and line endings.
Case 5: Claude put a placeholder ellipsis in old_string
On long files, Claude sometimes writes something like // ...existing code... inside old_string. The placeholder exists only in Claude's head, so it can never match.
Do not put placeholders such as "// ...existing code..." in old_string.
Copy a literal substring that exists verbatim in the file.If it keeps happening, ask for the whole function or block as old_string. A complete block is more likely to be unique than a short fragment, and leaves less room for misremembering.
Case 6: a Read line number slipped into old_string
Read hands Claude the file with a line number in front of every line. If Claude mistakes that number and its separator for content and copies it into old_string, the result is a string that exists nowhere in the file. When you see an old_string with digits or a marker sitting just before the indentation, suspect this mix-up.
Do not include Read's line numbers or separators in old_string.
Copy only the text after the line number, indentation included.The exact prefix format varies by version and display, so rather than memorize it, I just check whether old_string starts with a number.
If one file keeps failing, the file may simply be too big
When the multiple-match error comes from the same file again and again, the file itself may have grown too large. Past roughly 800–1,000 lines of TypeScript or Python, repeated patterns become unavoidable and short snippets stop being unique.
The remedy is structural: split into modules, separate responsibilities, pull shared logic into helpers. A smaller file needs less context to be unambiguous.
A cheap habit that also helps: put a table of contents comment at the top of long files, like // 1) Auth handlers 2) Cache 3) HTTP client. It gives Claude a map and a better aim.
The quickest recovery once the error appears
Start by feeding Claude the output of grep:
# Step 1: see where the string occurs, and how many times
grep -n "the literal string" path/to/file.ts
# Step 2: if it appears more than once, print the surroundings
sed -n '10,20p' path/to/file.ts
# Step 3: ask Claude to rebuild old_string with 2 lines of context above and belowShowing Claude only the error message tends to produce another guess without re-reading the file. Pair it with the grep output — "I want line 14 of these matches; build an old_string with two lines of context on each side" — and the retry usually lands the first time.
Three misunderstandings worth correcting
First: "Claude can't tell when the file was reformatted." As above, Claude Code detects writes after a Read and stops with modified since read. That stop isn't a malfunction; it's the guard that keeps a stale copy from being written over the real one.
Second: "replace_all: true makes the multiple-match problem go away." The error goes away. What also goes away is your protection against accidental matches. It's for when you've confirmed you want every occurrence changed.
Third: "Once a file is read, it stays read for the whole conversation." There's a GitHub report of File has not been read yet appearing on already-read files after context compaction (#85488). If edits stall right after a compaction, re-reading is the quickest way through.
Other editors face the same constraint
This isn't unique to Claude Code. From what I can check, other agent-style editors also need some way to pin down the target inside a file. The error wording differs, but the need for a reliable anchor is shared. Context-bracketed old_string, a change plan before multi-location edits, and a full rewrite for structural changes should carry over to other tools.
When nothing above works
Work through this order. First, /clear and start again from a Read. If that fails, have Claude Write the whole file. After ten failed Edit attempts, one full rewrite beats the eleventh in both time and accuracy.
Where you're likely to trip next
Once a single Edit goes through, the next thing people hit is the second and third edits in a row failing. The first edit makes the next old_string stale; I walk through that in fixing cascading failures in sequential Edits.
If not found keeps happening on a long file, Claude may not have read the whole thing. It's worth running through when Read doesn't reach the end of a large file once. And if you move formatting into PostToolUse, the trade-offs between hook events are in design decisions for Claude Code Hooks.
Your next step
If you try one thing today, run cat -A filename | head -20 on the file that won't take an edit. Tabs, CRLF or trailing whitespace will explain most cases right there. If nothing shows up, count the matches with grep -n.
If the count is more than one, add context; if it's zero, doubt the file. That two-way split is the one thing I refuse to drop, even on a tired night.
Committing .editorconfig and .gitattributes cut my own Edit failures down noticeably. I'm still looking for the best setup, but if you're tripping over the same spots, I hope this makes your next session flow a little more smoothly.