[sed] Back up a file before editing it in place

Created on November 30, 2026

Add a suffix to -i to keep a backup when sed edits a file in place. Suppose fruits.txt contains these lines.

apple
orange

Run the substitution with -i.bak.

sed -i.bak 's/apple/grape/' fruits.txt

The edited fruits.txt contains the new text.

grape
orange

The original text is saved in fruits.txt.bak.

apple
orange
Bash Shell command sed