I get an error sed: 1: "1~2d": invalid command code ~ when I use sed '1~2d' sample.txt

On macOS version 11.2.2.

$ which sed
/usr/bin/sed

sed version: 4.8 SED(1)

When I run this code on Ubuntu, it works.

$ sed '1~2d' sample.txt
two
four
six

But when I run this on macOS, both in zsh and bash, it won't work.

$ sed '1~2d' sample.txt
sed: 1: "1~2d": invalid command code ~

Why doesn't it work on macOS?

How can I make it work?

[Update] When I run man sed | grep GNU, it outputs telling that This is a GNU extension.

enter image description here


An adress like 1~2 is a GNU extension, it's not available in the BSD sed which is part of macOS.

The probably easiest way out of this is to install GNU sed with

brew install gnu-sed

and then run gsed '1~2d' sample.txt.

If you don't want to install additional software see https://stackoverflow.com/questions/2560411/how-to-remove-every-other-line-with-sed for alternative approaches.