Skip to content
DevOps AI ToolKit
Newsletter
All prompts
AI for Bash & Python Automation Difficulty: Intermediate ClaudeChatGPTCursor

Bash Safe In-Place sed Edit Wrapper Prompt

Build a Bash wrapper around sed -i that backs up, validates, and atomically applies in-place edits so a bad expression can never corrupt or truncate config files

Target user
engineers who automate ops with Bash and Python
Difficulty
Intermediate
Tools
Claude, ChatGPT, Cursor

The prompt

You are a senior automation engineer who has watched a stray `sed -i` expression silently blank out a production config, and you now wrap every in-place edit in a safety harness.

I will provide:
- The file(s) to edit and the sed expression(s) or substitution intent
- Whether GNU sed or BSD/macOS sed is the target (the `-i` syntax differs)
- Any validation the file must pass after editing (syntax check, must-still-contain markers)

Your job:

1. **Never edit in place blind** — write to a temp file via `mktemp`, run sed reading the original and writing the temp, then atomically `mv` the temp over the original only after checks pass. Keep a timestamped `.bak` copy.
2. **Handle sed portability** — detect GNU vs BSD sed and emit the correct `-i` form (or avoid `-i` entirely by using the temp-file approach so it works on both).
3. **Validate before committing** — refuse to replace the original if the edit produced an empty file, if line count dropped more than a configurable threshold, or if a required post-condition (e.g. `grep -q` for a marker, `bash -n` / `nginx -t` syntax check) fails; restore from the `.bak` on any failure.
4. **Preserve metadata** — retain the original file's owner, group, and permissions on the replacement.
5. **Report** — print a unified `diff` of what changed and exit non-zero if nothing changed when a change was expected.

Output as: the full script in strict mode (`set -euo pipefail`) in one fenced block, followed by example invocations and a note on rollback.

Default to non-destructive: always back up first, validate before the atomic swap, and restore automatically if validation fails.

Run this prompt with AI

Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.

Related prompts

More Bash & Python Automation prompts & error guides

Browse every Bash & Python Automation prompt and troubleshooting guide in one place.

Free download · 368-page PDF

Reading prompts? Get all 500 in one free PDF

500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.

  • 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
  • Instant PDF download — yours free, forever
  • Plus one practical AI-workflow email a week (no spam)

Single opt-in · unsubscribe anytime · no spam.