This prompt is designed for AI coding agents that need to perform a single, unambiguous text replacement within a known file. The core job-to-be-done is a surgical edit: given a specific instruction like 'rename the function getCwd to getCurrentWorkingDirectory in src/utils.py', the agent must produce a verifiable plan before acting. The ideal user is a developer or an AI engineer integrating a coding agent into a product where edit precision is non-negotiable. Required context includes the exact file path, the precise string to find, and the exact replacement string. Without this context, the prompt cannot enforce its primary guardrail: an exact-match uniqueness check.
Prompt
Safe Search-and-Replace Prompt Template

When to Use This Prompt
Defines the precise job-to-be-done for the Safe Search-and-Replace Prompt Template, the ideal user, required context, and when not to use it.
Use this prompt when the edit instruction is concrete and the target location is known. It is the right tool for renaming a single symbol, updating a hardcoded value, or fixing a specific typo. The prompt forces the agent to output a plan containing the exact match string, a confirmation that the string appears exactly once in the file, and a dry-run diff. This prevents the agent from making blind, ambiguous, or scattershot edits that corrupt a codebase. For example, if you ask an agent to 'update the API version to v2', this prompt will force it to locate the single line where the version is defined, confirm no other occurrences exist, and show you the one-line change before it is applied.
Do not use this prompt for multi-file refactors, fuzzy find-and-replace, or generating new code blocks. It is explicitly not designed for tasks like 'update all error handling to use the new Result type across the project' or 'add a new endpoint to the controller.' Those tasks require a different class of prompts focused on patch planning, multi-file edit consistency, and impact scope analysis. Using this prompt for broad changes will result in a failed uniqueness check, causing the agent to halt and request more specific instructions. The next step after reading this section is to review the prompt template itself and understand how to wire the exact-match and dry-run constraints into your agent's execution loop.
Use Case Fit
Where the Safe Search-and-Replace Prompt Template works well and where it introduces risk. Use these cards to decide if this prompt fits your workflow before wiring it into an automated agent.
Good Fit: Targeted String Replacement
Use when: you need to replace a known, specific string with a new value across one or more files. Guardrail: the prompt requires an exact match string, which forces the agent to locate the precise text before generating a replacement plan.
Bad Fit: Semantic Refactoring
Avoid when: the change requires understanding code semantics, such as renaming a variable across scopes or refactoring a function signature. Guardrail: use a dedicated refactoring prompt with AST awareness instead. Search-and-replace operates on raw text, not parsed structure.
Required Input: Exact Match String
Risk: ambiguous or partial match strings cause unintended replacements. Guardrail: the prompt template requires a verbatim match string with surrounding context lines. Validate uniqueness before execution by running a dry-run diff that surfaces all match locations.
Operational Risk: Unintended Matches
Risk: the match string appears in unexpected locations, such as comments, string literals, or generated files. Guardrail: the prompt includes a uniqueness check step. If multiple matches are found, the agent must report them and request scope narrowing before applying changes.
Operational Risk: Whitespace and Encoding Drift
Risk: invisible differences in tabs, spaces, line endings, or encoding cause match failures or silent mismatches. Guardrail: the prompt should include a pre-check that normalizes whitespace for comparison and reports encoding mismatches before attempting replacement.
Bad Fit: Multi-File Coordinated Changes
Avoid when: a single logical change spans multiple files with interdependent edits. Guardrail: use a multi-file edit consistency prompt instead. Search-and-replace treats each file independently and cannot verify cross-file coherence.
Copy-Ready Prompt Template
A reusable prompt with square-bracket placeholders for coding agents to perform targeted text replacements with guardrails, uniqueness checks, and dry-run diffs before applying changes.
This prompt template instructs a coding agent to perform a safe search-and-replace operation on a specified file. It requires the agent to locate the exact match string, verify uniqueness, produce a dry-run diff, and only apply the change after confirming no unintended matches exist. Use this template when you need a single, auditable text replacement with built-in safety checks—not for multi-file refactors or complex AST transformations.
textYou are a coding agent performing a safe search-and-replace operation. Follow these steps in order and stop if any check fails. ## Inputs - File path: [FILE_PATH] - Search string (exact match): [SEARCH_STRING] - Replacement string: [REPLACEMENT_STRING] - Expected match count: [EXPECTED_MATCH_COUNT] - Context lines before match (optional): [CONTEXT_BEFORE] - Context lines after match (optional): [CONTEXT_AFTER] ## Constraints - [CONSTRAINTS] ## Procedure 1. Read the file at [FILE_PATH] and compute its SHA-256 hash. Record this as the pre-edit hash. 2. Search for [SEARCH_STRING] as an exact substring match. Count all occurrences. 3. If the match count does not equal [EXPECTED_MATCH_COUNT], stop and report the discrepancy. Include line numbers for every match found. 4. If [CONTEXT_BEFORE] or [CONTEXT_AFTER] are provided, verify that the surrounding lines of the target match contain the specified context. Stop if context verification fails. 5. Generate a unified diff showing the proposed change. This is the dry-run diff. Do not modify the file yet. 6. Review the dry-run diff for unintended changes, whitespace noise, or scope creep. If any issue is found, stop and report it. 7. If all checks pass, apply the replacement and write the file. 8. Compute the SHA-256 hash of the modified file. Record this as the post-edit hash. 9. Verify that the replacement appears exactly once in the modified file (or [EXPECTED_MATCH_COUNT] times if replacing all occurrences). 10. Generate a reverse patch that restores the original content and verify it applies cleanly. ## Output Schema Return a JSON object with this structure: { "file_path": "string", "pre_edit_hash": "string", "post_edit_hash": "string", "match_count_found": number, "match_count_expected": number, "context_verified": boolean, "dry_run_diff": "string (unified diff format)", "applied": boolean, "reverse_patch": "string (unified diff format)", "reverse_patch_verified": boolean, "errors": ["string"] } ## Risk Level [RISK_LEVEL]
Adapt this template by filling each square-bracket placeholder with concrete values. For [CONSTRAINTS], add file-specific rules such as 'do not modify lines containing import statements' or 'preserve trailing commas.' Set [RISK_LEVEL] to 'low', 'medium', or 'high' to control whether the agent should escalate for human review before applying changes. For high-risk files, pair this prompt with a human-in-the-loop handoff that presents the dry-run diff for approval. Always test this prompt against a copy of the target file first, and validate that the reverse patch restores the original content exactly before trusting it in automated pipelines.
Prompt Variables
Required inputs for the Safe Search-and-Replace Prompt Template. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to programmatically verify the input before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[FILE_PATH] | Absolute or repository-relative path to the target file | src/services/payment/handler.ts | Check file exists on disk; verify path is within allowed repository boundary; reject symlinks to external locations |
[SEARCH_BLOCK] | Exact text block to find and replace, including all whitespace and indentation | function calculateTotal(items) { return sum(items); } | Must be unique within the file; validate via exact string match count; if count != 1, reject and request disambiguation |
[REPLACEMENT_BLOCK] | Exact text to insert in place of the search block | function calculateTotal(items: Item[]): number { return sum(items) * 1.08; } | Must differ from [SEARCH_BLOCK]; validate non-identity; check for parse validity if file type is known structured format |
[EXPECTED_MATCH_COUNT] | Number of times the search block should appear in the file | 1 | Must be a positive integer; if null, default to 1; if >1, require explicit confirmation flag before applying multiple replacements |
[FILE_ENCODING] | Character encoding of the target file | utf-8 | Validate against detected encoding via chardet or equivalent; reject if mismatch would corrupt non-ASCII characters |
[BACKUP_PATH] | Path where pre-edit backup copy will be written | src/services/payment/handler.ts.bak.2025-01-15 | Ensure backup directory exists and is writable; verify backup file does not already exist to prevent overwrite; hash backup after write |
[DRY_RUN_FLAG] | Boolean controlling whether to simulate or apply the edit | Must be true or false; if true, return predicted diff only; if false, apply edit after uniqueness and backup checks pass | |
[CONTEXT_WINDOW_LINES] | Number of lines before and after the match to include in verification output | 5 | Must be a non-negative integer; used to generate surrounding context in diff output for human review; 0 returns only the changed lines |
Implementation Harness Notes
How to wire the Safe Search-and-Replace prompt into a production coding agent with validation, retries, and safety gates.
The Safe Search-and-Replace prompt is designed to be called as a single step within a larger agent loop, not as a standalone chat interaction. Your application should invoke this prompt when a coding agent has determined that a targeted text replacement is the correct action. The prompt expects a structured input payload containing the file path, the current file content, the replacement intent, and any constraints such as uniqueness requirements or scope boundaries. Do not call this prompt for multi-file refactors, wholesale rewrites, or cases where the replacement target cannot be expressed as an exact string match. Those scenarios require the Patch Planning or Multi-File Edit Consistency prompts instead.
Wire the prompt into your agent harness with a pre-invocation validation layer. Before calling the model, verify that the file exists, that the current content hash matches the hash provided in the input, and that the file is not on a deny list of generated or vendor-managed paths. After receiving the model's structured output, parse the replacement plan and run automated checks: confirm that every search string appears exactly once in the target file, that no search string is a substring of another search string, and that the proposed replace text does not introduce syntax errors for the file type. For high-risk files such as production configuration, security policies, or database migration scripts, route the replacement plan to a human approval queue before any file modification occurs. Log the full prompt input, model output, validation results, and approval decision to your audit trail.
Apply the replacement using a transactional file operation: write the modified content to a temporary file, compute its hash, and only atomically replace the original file after confirming the write succeeded. Immediately run a post-edit verification by calling the Post-Edit Diff Verification prompt, comparing the actual diff against the expected change. If the diff contains unintended modifications, whitespace noise, or scope creep beyond the declared replacement, invoke the Rollback Decision prompt to determine whether to revert, retry with tighter constraints, or escalate. For batch replacements across multiple files, serialize the operations and verify each file individually before proceeding to the next. Never apply a second replacement until the first file's verification passes. The most common production failure mode is a search string that matches zero or multiple locations due to file drift between the snapshot and the edit attempt—always gate on exact match uniqueness before touching the file.
Expected Output Contract
Validation rules for the JSON response produced by the Safe Search-and-Replace prompt. Use this contract to parse, validate, and gate the model output before applying any file modifications.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
plan_id | string (UUID v4) | Must parse as a valid UUID v4. Used for audit trail correlation. | |
file_path | string (relative path) | Must resolve to a file within the repository root. Path traversal sequences (../) are disallowed. | |
search_string | string | Must be non-empty. An exact uniqueness check must confirm zero or one match in the target file before application. | |
replace_string | string | May be empty (for deletions). Length must not exceed 10x the search_string length without explicit approval. | |
uniqueness_check | object | Must contain 'occurrences' (integer >= 0) and 'is_unique' (boolean). If occurrences > 1, the plan must be rejected. | |
dry_run_diff | string (unified diff format) | Must parse as a valid unified diff. The diff must show exactly one hunk modifying only the lines containing search_string. | |
pre_edit_hash | string (SHA-256 hex) | Must be a 64-character hex string. Must match the computed SHA-256 of the target file before the edit is applied. | |
post_edit_expected_hash | string (SHA-256 hex) | Must be a 64-character hex string. After applying the replacement, the new file hash must match this value exactly. |
Common Failure Modes
What breaks first when using search-and-replace prompts in production coding agents, and how to guard against each failure mode.
Ambiguous Match Collisions
Risk: The search string matches multiple locations in the file, causing the agent to replace the wrong instance or all instances when only one was intended. This is the most common production failure in search-and-replace workflows. Guardrail: Require the agent to report match count and line numbers before applying changes. Add a uniqueness constraint to the prompt template that forces the agent to include enough surrounding context lines to make the match string unique. Validate that the reported match count equals exactly 1 before proceeding.
Whitespace and Formatting Mismatch
Risk: The search string fails to match because of invisible differences in indentation (tabs vs spaces), trailing whitespace, or line ending variations between what the agent constructs and what exists in the file. Guardrail: Normalize whitespace before comparison by trimming trailing spaces and standardizing indentation characters. Include a pre-check step that reads the target lines with visible whitespace markers. Add eval criteria that test search strings against files with mixed tab/space indentation.
Silent No-Op When Search Fails
Risk: The search string doesn't match anything in the file, but the agent reports success without verifying the replacement actually occurred. The file remains unchanged while the agent proceeds as if the edit was applied. Guardrail: Require a post-replacement verification step that confirms the new content exists in the file and the old content no longer appears. Compare file hashes before and after. If the hash is unchanged, fail loudly and escalate rather than continuing silently.
Scope Creep Beyond Target Region
Risk: The replacement text accidentally modifies code outside the intended function, class, or block because the search context was too broad or the replacement introduced unintended side effects. Guardrail: Enforce boundary constraints in the prompt that specify exactly which function, class, or line range may be modified. Run a post-edit diff that flags any changes outside the declared scope. Use edit boundary enforcement checks that compare the actual diff against the permitted region.
Encoding and Special Character Corruption
Risk: Non-ASCII characters, Unicode symbols, regex metacharacters, or escape sequences in the search or replacement strings cause malformed output or failed matches. Common with configuration files, localized strings, or code containing string literals with backslashes. Guardrail: Treat search and replacement strings as literal text, not regex patterns. Validate file encoding before and after edits. Add eval test cases with Unicode, emoji, and escape-heavy strings. Verify the file parses correctly after modification.
Partial Application Leaving Inconsistent State
Risk: When multiple search-and-replace operations are chained, a failure mid-sequence leaves the file in an inconsistent state with some edits applied and others missing. The agent may not detect the partial failure. Guardrail: Wrap multi-step edits in a transactional pattern: snapshot the file first, apply all replacements to a copy, verify the complete set, and only then overwrite the original. If any step fails, roll back to the snapshot. Include eval checks for atomicity across multi-edit sequences.
Evaluation Rubric
How to test output quality before shipping. Use this rubric to evaluate whether the safe search-and-replace prompt produces a replacement plan that is safe, precise, and verifiable.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Match uniqueness | Each [SEARCH_STRING] occurs exactly once in [TARGET_FILE] or [TARGET_REGION] | Ambiguous match: search string found 0 or >1 times in target scope | Run grep -c for each search string against the target file; assert count == 1 |
Replacement scope isolation | Replacement affects only the lines specified in the plan; no adjacent or unrelated lines modified | Diff contains hunks outside declared line ranges or touching unchanged neighbors | Apply the plan in dry-run mode; diff --unified=0 and verify hunk boundaries match plan exactly |
Dry-run diff accuracy | Dry-run diff matches the predicted diff in the plan with zero deviation | Applied diff differs from predicted diff in content, line count, or hunk count | Capture dry-run output; compare with predicted diff using diff or cmp; assert no differences |
Syntax validity after replacement | Modified file passes language-specific syntax check or parse without errors | Parser, linter, or compiler reports syntax error on modified file | Run language-appropriate syntax validator (e.g., python -m py_compile, eslint --no-eslintrc, ruby -c); assert exit code 0 |
No unintended matches in related files | Search strings do not appear in any file outside the declared modification scope | Search string found in sibling files, configs, or generated code not listed in the plan | Run grep -r for each search string across the repository; assert matches only in declared target files |
Backup integrity | Backup file is byte-for-byte identical to the original file before edit | Backup missing, truncated, or hash mismatch with pre-edit state | Compute SHA-256 of backup and original pre-edit file; assert hashes match |
Rollback round-trip fidelity | Applying the reverse patch restores the file to its exact pre-edit state | Reverse patch fails to apply, or restored file differs from original | Apply forward patch, then reverse patch; diff original against restored; assert no differences |
Plan completeness | Plan includes all required fields: search strings, replacements, target files, predicted diff, uniqueness confirmation, and rollback commands | Plan missing one or more required fields or contains unresolved placeholders | Validate plan output against a JSON Schema or field checklist; assert all required fields present and non-null |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base template with a single file and relaxed uniqueness checks. Replace the dry-run diff requirement with a simpler 'show me what would change' instruction. Drop the hash verification step and rely on manual review.
codeYou are a precise search-and-replace agent. Given [FILE_CONTENT] and [SEARCH_STRING], produce: 1. The exact match location (line numbers) 2. The proposed [REPLACEMENT_STRING] 3. A before/after snippet showing only the changed lines If [SEARCH_STRING] appears more than once, list all occurrences and ask which to replace.
Watch for
- Multiple matches silently replaced without confirmation
- Whitespace or indentation mismatches causing missed matches
- No rollback path if the replacement is wrong

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us