Preview and apply literal text replacements with sd
Review a literal replacement through standard input, keep a backup, and apply the same sd expression to a file.
Updated
in short
Send a file through standard input to inspect the transformed text. After checking it, run the same expression with a filename to change that file.
Work through these disposable fixtures before adapting the commands to your own files. Run the steps in the same terminal session.
Tools used
Before you start
- Bash on Linux or macOS
- The listed tools installed and available on PATH
Steps
Step 1: Create an endpoint configuration
These are sample hostnames and never receive network requests.
shtrmn_guide_dir="$(mktemp -d)" cd "$trmn_guide_dir" printf 'API=https://old.example/v1\nDOCS=https://old.example/help\n' > endpoints.env cp endpoints.env endpoints.env.beforeStep 2: Inspect the replacement without writing the file
-F makes both arguments literal strings. Redirecting input leaves endpoints.env unchanged.
shsd -F 'https://old.example' 'https://new.example' < endpoints.envoutputAPI=https://new.example/v1 DOCS=https://new.example/help
Step 3: Check that the source is unchanged
cmp exits successfully when the files match.
shcmp endpoints.env endpoints.env.before && printf 'source unchanged\n'outputsource unchanged
Step 4: Apply the reviewed replacement
Giving sd a filename changes the file in place. Keep the backup until you have checked the result.
shsd -F 'https://old.example' 'https://new.example' endpoints.env cat endpoints.envoutputAPI=https://new.example/v1 DOCS=https://new.example/help
Further reading
[sd usage](https://github.com/chmln/sd) [sd command reference](https://github.com/chmln/sd/tree/master/sd-cli)
FAQ
- Why choose -F for URLs?
- A dot has special meaning in a regular expression. Literal mode matches the exact hostname and path characters.
- How can I restore this fixture?
- Copy endpoints.env.before back to endpoints.env. For project files, review the change through your existing version-control workflow.