In-place edits with sed on OS X

SundayMonday picture SundayMonday · Sep 27, 2011 · Viewed 102.6k times · Source

I'd like edit a file with sed on OS X. I'm using the following command:

sed 's/oldword/newword/' file.txt

The output is sent to the terminal. file.txt is not modified. The changes are saved to file2.txt with this command:

sed 's/oldword/newword/' file1.txt > file2.txt

However I don't want another file. I just want to edit file1.txt. How can I do this?

I've tried the -i flag. This results in the following error:

sed: 1: "file1.txt": invalid command code f

Answer

whittle picture whittle · Sep 27, 2011

You can use the -i flag correctly by providing it with a suffix to add to the backed-up file. Extending your example:

sed -i.bu 's/oldword/newword/' file1.txt

Will give you two files: one with the name file1.txt that contains the substitution, and one with the name file1.txt.bu that has the original content.

Mildly dangerous

If you want to destructively overwrite the original file, use something like:

sed -i '' 's/oldword/newword/' file1.txt
      ^ note the space

Because of the way the line gets parsed, a space is required between the option flag and its argument because the argument is zero-length.

Other than possibly trashing your original, I’m not aware of any further dangers of tricking sed this way. It should be noted, however, that if this invocation of sed is part of a script, The Unix Way™ would (IMHO) be to use sed non-destructively, test that it exited cleanly, and only then remove the extraneous file.