BSD sed vs. GNU sed, and -i

7,923

Solution 1

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

Solution 2

You have to specify a backup file, like:

sed -i .bak 's/original/new/g' maths.tx  
Share:
7,923

Related videos on Youtube

Kam
Author by

Kam

Updated on September 18, 2022

Comments

  • Kam
    Kam over 1 year

    Unix iMac shell terminal

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

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

    • Michael Homer
      Michael Homer over 6 years
    • Jeff Schaller
      Jeff Schaller over 6 years
      I don't have a Mac to test with; why does it complain about working on stdin when you've provided a file to process? Was the command instead sed -i 's/original/new/g' < maths.txt (note the addition of the less-than sign)
    • mbaljeetsingh
      mbaljeetsingh over 3 years
      I have a Linux/macOS/BSD solution to this in my answer stackoverflow.com/a/65497543/117471
  • Pankaj Goyal
    Pankaj Goyal over 6 years
    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.
  • Kusalananda
    Kusalananda over 6 years
    @Kam Good! If this solves your issue, please consider accepting the answer.