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.

how-to4 steps

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

  1. Step 1: Create an endpoint configuration

    These are sample hostnames and never receive network requests.

    sh
    trmn_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.before
  2. Step 2: Inspect the replacement without writing the file

    -F makes both arguments literal strings. Redirecting input leaves endpoints.env unchanged.

    sh
    sd -F 'https://old.example' 'https://new.example' < endpoints.env
    output
    API=https://new.example/v1
    DOCS=https://new.example/help
  3. Step 3: Check that the source is unchanged

    cmp exits successfully when the files match.

    sh
    cmp endpoints.env endpoints.env.before && printf 'source unchanged\n'
    output
    source unchanged
  4. Step 4: Apply the reviewed replacement

    Giving sd a filename changes the file in place. Keep the backup until you have checked the result.

    sh
    sd -F 'https://old.example' 'https://new.example' endpoints.env
    cat endpoints.env
    output
    API=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.

related