11

Unix iMac shell terminal

sed -i 's/original/new/g' maths.tx  

Message returned: sed: -i may not be used with stdin

DopeGhoti
  • 76,081
Kam
  • 111

2 Answers2

20

Macs use the BSD version of utilities such as sed and date, which have their own idiosyncrasies.

In this specific case, the BSD build of sed mandates the extension for the backup file with -i, rather than it being optional, as in GNU sed.

As such:

sed -i .bak 's/needle/pin/g' haystack

The shown command will replace all instances of needle with pin in the file haystack, and the original file will be preserved in haystack.bak.

From the manual for the implementation of sed on a Mac:

-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.

As opposed to on a Linux host:

  -i[SUFFIX], --in-place[=SUFFIX]
      edit files in place (makes backup if SUFFIX supplied)

Note that "a zero-length extension" is distinct from "no extension". You can eschew the backup entirely, then, with:

sed -i '' 's/needle/pin/g' haystack
DopeGhoti
  • 76,081
  • that seem to work for my Mac sed -i '' – Kam Nov 03 '17 at 14:25
  • 1
    I'm glad it worked. Welcome to U&L! If this answer was helpful, please 'Accept' the answer so that people perusing questions know that it has been answered and can find a solution here. – DopeGhoti Nov 03 '17 at 16:14
  • 4
    @Kam Good! If this solves your issue, please consider accepting the answer. – Kusalananda Feb 08 '18 at 11:34
  • 1
    Accurate answer, just what I was looking for, I want to say that many utilities on the osx are different from GNU, for example, also grep utility. Please mark this answer as accepted. – user991 Oct 01 '20 at 18:36
  • I'd add, if you want something portable (GNU and BSD sed), you might want to write sed -i.bak ... (no space, and a dot). This leads to create a backup file. If you don't want it, as you know the filename anyway, it's easy to add a && rm filename.ext.bak after the sed. This way works on both sed versions. – zezollo Aug 16 '22 at 16:50
  • sed -i .bak is also portable, for the record. The space is optional. As, for that matter, is the .; it's just that if you do sed -i bak for a file file, the backup would then be called filebak which some might not find as readable. – DopeGhoti Aug 16 '22 at 20:04
3

You have to specify a backup file, like:

sed -i .bak 's/original/new/g' maths.tx  
Ipor Sircer
  • 14,546
  • 1
  • 27
  • 39