Sed inline editing different on Mac OSX?

18 September 2012 — 4 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 🙂

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

What do you think?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s