◉CLAUDE LABJP
●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through
Articles/Claude Code
⟐ Claude Code/2026-05-24Intermediate

When Claude Code's Sequential Edits Cascade into Failure — Fixing 'old_string not found' and 'not unique' on the Same File

Run several Edits against the same file and the second or third one fails with 'not found', 'Found 2 matches' or 'modified since read'. A triage table for five error messages, a match-counting script, when to use replace_all or sed, and moving formatter hooks to Stop.

claude-code135edit-tool3troubleshooting108error17diff

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:

  1. Claude reads the file once with Read.
  2. From that snapshot, it generates old_string for Edits 1, 2 and 3 together.
  3. Edit 1 applies, and the targeted text on disk becomes its new_string.
  4. Edit 2's old_string is still based on the Read snapshot.
  5. If Edit 1 removed what Edit 2 was looking for, the string simply isn't there (not found).
  6. If Edit 1's new_string added 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 causeHow to checkFix
String to replace not found in fileAn earlier Edit rewrote that spot, or tabs/spaces differRun the counting script below; look at whitespace with cat -AInsert a Read, then Edit only what remains
Found 2 matches of the string to replace, but replace_all is falseAn earlier new_string copied the pattern, or the line already repeatsPrint the count and line numbers with the scriptWiden 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 linterA formatter, hook or your editor rewrote the file after the ReadLook for formatter hooks in /hooks; suspect editor autosaveRe-read, and keep formatters from running between Edits
File has been unexpectedly modifiedAn IDE extension or file watcher re-saved the file (sometimes only the mtime changes)Close the file in your editor and retryPause editor-side format-on-save while Claude works
File has not been read yet. Read it first before writing to itThe file was never read, or the read record dropped in a long sessionCheck whether a Read precedes the EditAsk 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, Read the 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.

ApproachGood forRisky whenHow to verify
Widen old_stringYou want to change exactly one spotThe surrounding code repeats too, so widening doesn't make it uniqueThe counting script reports 1
Edit with replace_all: trueEvery copy in one file should change the same wayThe same text also lives in comments or string literalsRead every line of git diff
Bash + sed -iMechanical replacement across several filesThe term has regex metacharacters, or you'll Edit the same file right afterCompare 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

  1. Sort the error into one of the five shapes in the table above.
  2. For not found, check whether the previous Edit touched the same region.
  3. For Found N matches, look at whether the recent new_string copied the pattern.
  4. For modified since read or unexpectedly modified, check /hooks and your editor's autosave.
  5. 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, tightly

If --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.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

⟐ Claude Code2026-05-02
Two Reasons Claude Code's Edit Tool Refuses — Multiple Matches vs. No Match
Claude Code's Edit tool fails in two distinct ways: the string matches in several places, or it matches nowhere. Here is how to tell them apart, how to build a good old_string, and how to check for formatters, line endings and invisible characters.
⟐ Claude Code2026-11-03
When Claude Code dies with a Bus error on a shared home directory, check this before you turn off auto-update
Why Claude Code crashes with a Bus error on an NFS-style shared home, how the official cleanup rule and update switches work, and two small scripts to check your setup.
⟐ Claude Code2026-05-10
When Claude Code's Read Doesn't Reach the End of a File — Catching the PARTIAL view Notice and Sizing offset/limit
When Read returns only part of a large file, Claude Code says so with a PARTIAL view notice. Here is how to catch it, and how to size offset and limit by byte budget rather than line count, with measurements from my own sandbox.