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. 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.
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. From its side there is no way to notice the file changed.
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, I turn formatOnSave off while pairing with Claude, or move formatting into a pre-commit hook so the two don't trample each other mid-session.
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.
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.
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.
Sometimes the environment is the thing to suspect. For a broad check of settings and permissions, Claude Code's /doctor self-diagnosis is a good place to begin. If shell commands are failing alongside Edit, the cause may overlap with the patterns in Claude Code Bash tool execution errors.
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.