BSD sed: extra characters at the end of d command

lutaoact picture lutaoact · Sep 28, 2014 · Viewed 8.8k times · Source

I use sed command on mac OS, following is the text.

$ cat pets.txt 
This is my cat
  my cat's name is betty
This is your dog
  your dog's name is frank
This is your fish
  your fish's name is george
This is my goat
  my goat's name is adam

when I run: (BSD sed)

$ sed '3,6 {/This/d}' pets.txt

It show error:

sed: 1: "3,6 {/This/d}": extra characters at the end of d command

what's wrong with it? when I use gsed(GNU sed), it works well.

Answer

user664833 picture user664833 · Jun 10, 2020

For anyone who found this question due to a similar error message, but caused by an attempt to in-place edit on Mac OS X

As per https://github.com/lmquang/til/issues/18:

OS X requires the extension to be explicitly specified. The workaround is to set an empty string:

$ sed -i '' 's/megatron/pony/g' /path/to/file.txt

         ^^

man sed:

-i extension

Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

So, there seems to be an issue on Mac OS X when extension is omitted, and so you have to supply -i with an empty string ('').

See also https://unix.stackexchange.com/a/112024/23614:

If using FreeBSD or OS/X, replace -i with -i ''.