sed Command Generator — Build & Decode sed Commands
Generate the sed command for find-and-replace, deleting lines or printing a
range — with every part explained and the -i macOS trap handled. Or paste
a sed command to decode it. Runs in your browser.
Your command
—
Or: decode a sed command
Paste any sed command — the script gets explained.
The substitute command, decoded
The workhorse is s/find/replace/flags: the s means substitute, the
slashes separate the parts, and the flags at the end tune it. g replaces every
match on a line (without it, only the first); I makes the match case-insensitive. So
sed 's/foo/bar/g' file swaps every foo for bar on each line.
The -i trap that wastes everyone an hour
-i edits the file in place instead of printing to the screen — but the two big sed
versions disagree on the syntax:
- GNU sed (Linux):
sed -i 's/a/b/' fileworks. - BSD sed (macOS): needs an argument for the backup suffix —
sed -i '' 's/a/b/' file. The empty''means "no backup". Forget it and you get a cryptic "command a expects \ followed by text" error.
Tick "I'm on macOS" above and the builder adds the '' for you.
Gotchas worth knowing
- The delimiter doesn't have to be
/. Replacing file paths gets ugly with slashes, so use another character:sed 's#/old/path#/new/path#g'. The builder switches the delimiter automatically when your text contains/. -ihas no undo. Run it without-ifirst to see the output, or use-i.bak(GNU) to keep a backup copy.- Special characters need escaping or
-E. Plain sed uses basic regex where+,?and()need backslashes. Add-Eto use them normally. - Printing needs
-n. sed prints every line by default, so to print only a range you suppress the default with-nand addp.
Frequently asked questions
How do I find and replace text with sed?
sed 's/old/new/g' file replaces every old with new. Add
-i to change the file in place (on macOS, -i '').
Why does sed -i fail on macOS?
BSD sed requires a backup-suffix argument after -i. Use sed -i '' 's/a/b/'
file — the empty string means no backup.
How do I delete lines matching a pattern?
sed '/pattern/d' file deletes every line containing the pattern. Add -i
to apply it to the file.
How do I replace a file path with sed?
Use a different delimiter so the slashes don't clash: sed 's#/usr/local#/opt#g' file.