Search code examples
macosunixsed

Order of options in Unix sed for editing files in-place


The man page for sed says the following:

sed [-Ealnru] command [-I extension] [-i extension] [file ...]

Based on this, I believe the following should work:

sed -E '/^A/d' -i '' tmp.txt 

where cat tmp.txt gives:

A
B

But the output is:

sed: -i: No such file or directory
sed: : No such file or directory
B

And tmp.txt has remained unchanged.

For the above command to work, I should instead do the following:

sed -E -i '' '/^A/d' tmp.txt 

My question is, why? What I tried first should have worked according to the man page. The order of options was just as described there. Yet it did not work.

I'm on a Mac running macOS 12, which is based on FreeBSD.


Solution

  • POSIX utility syntax guidelines specify that options -- including options with option-arguments -- should come before positional arguments. While a GNUish command-line parser will recognize options in later positions so long as there isn't an end-of-options sigil preceding them, this behavior (as you've observed) does not reliably extend to non-GNU implementations.

    This means that the documentation showing -i coming after the expression to run was faulty. Reorder your arguments as follows:

    sed -E -i '' '/^A/d' tmp.txt