Sed inline editing different on Mac OSX?

18 September 2012 — 5 Comments

Sed is very powerful, I use it a lot on Linux servers I manage. Today I was working on a local git repository on Mac OSX Mountain Lion when I run into some trouble.

Usually, to replace text in a file with new text I run:

sed -i 's/Find this text/Replace with this/' file_to_replace_in.txt

While this works on Linux, it does not on Mac OSX:

sed: -i may not be used with stdin

The manpage on OSX says:

Edit files in-place, saving backups with the specified extension.
If a zero-length extension is given, no backup will be saved.

Aha, it wants to save a backup file. So I changed my command to:

sed -i '.bak' 's/Find this text/Replace with this/' file_to_replace_in.txt

This works, although it leaves a backup file ‘file_to_replace_in.txt.bak’ behind. This is great if you’re not sure, but can be annoying as well. To stop it making backups you specify an empty extension, like so:

sed -i '' 's/Find this text/Replace with this/' file_to_replace_in.txt

This allows me to quickly find & replace again, like when working on Linux 🙂

5 responses to Sed inline editing different on Mac OSX?

  1. 

    werkt dit ook als sed aan het eind van een pipe staat? bij mij dus niet.

  2. 

    bovenstaande vraag slaat natuurlijk nergens op: “-i implies that you will be editing a file in place, not the stdin stream that you’re referring.” http://joemaller.com/823/quick-note-about-seds-edit-in-place-option/

  3. 

    Hey Remi,

    If you have homebrew just install gnu-sed and you will get the sed you are used to. You will need to place its path ahead of /usr/bin.

Trackbacks and Pingbacks:

  1. Home | MacarioJames.com - August 28, 2019

    […] so i was back to googling. I found out that the sed command operates slightly differently on Linux than it does on macOS. Ahh, but of […]

Leave a reply to offbooks Cancel reply