search_and_replace
The search_and_replace
tool finds and replaces text within a file, supporting both literal strings and regular expression patterns. It allows for targeted replacements across multiple locations, optionally within specific line ranges.
Parameters
Required Parameters
path
: The relative path (from the workspace saarthit) of the file to modify.search
: The text string or regex pattern to find.replace
: The text to replace matches with.
Optional Parameters
start_line
: The 1-based line number where the search scope begins.end_line
: The 1-based line number where the search scope ends (inclusive).use_regex
: Set to"true"
to treat thesearch
parameter as a regular expression pattern (default isfalse
).ignore_case
: Set to"true"
to perform a case-insensitive search (default isfalse
).
What It Does
This tool reads the specified file and performs a search-and-replace operation based on the provided parameters. It can operate on the entire file or be restricted to a specific range of lines. Changes are presented in a diff view for user review and approval before being saved.
When is it used?
- When renaming variables, functions, or classes across a file.
- When updating specific text strings or values consistently.
- When applying patterned changes using regular expressions.
- When refactoring code requires replacing specific patterns.
- When making targeted changes within a defined section of a file.
Key Features
- Flexible Searching: Supports both literal text and regular expression patterns.
- Case Sensitivity Control: Option to ignore case during search.
- Scoped Replacements: Can limit replacements to a specific range of lines (
start_line
,end_line
). - Global Replacement: Performs replacements across the entire file (or specified range) by default.
- Interactive Approval: Shows proposed changes in a diff view for user review and approval.
- User Edit Support: Allows editing the proposed content directly within the diff view.
- Context Tracking: Records the file edit operation.
- Error Handling: Checks for missing parameters, file access issues, and invalid line numbers.
Limitations
- Single File Operation: Operates on only one file at a time. Use
search_files
to find patterns across multiple files first. - Review Overhead: The mandatory diff view approval adds an interactive step.
- Regex Complexity: Complex regex patterns might require careful construction and testing.