Skip to content

replace_in_file — regex replace in a single file

replace_in_file runs re.subn(pattern, replacement, contents) over a single file and writes the result back. Unlike edit_file, it tolerates multiple matches; unlike apply_patch, it works on one file at a time.

ArgTypeRequiredDescription
pathstringyesRelative or absolute path. The file must exist.
patternstringyesRegex pattern (Python re flavor).
replacementstringyesReplacement string. Supports \1, \2, … backreferences.
{
"path": "src/app.py",
"pattern": "DEBUG\\s*=\\s*True",
"replacement": "DEBUG = False"
}
from chimera.tools.replace_in_file import ReplaceInFileTool
tool = ReplaceInFileTool()
result = tool.execute(
{"path": "docs/changelog.md",
"pattern": r"v(\d+)\.(\d+)\.0",
"replacement": r"v\1.\2.1"},
env=local_env,
)
3 replacements made in docs/changelog.md

If the pattern matches nothing:

0 replacements made in docs/changelog.md

(no error — count == 0 is just reported).