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
You can use the
-iflag correctly by providing it with a suffix to add to the backed-up file. Extending your example:Will give you two files: one with the name
file1.txtthat contains the substitution, and one with the namefile1.txt.buthat has the original content.Mildly dangerous
If you want to destructively overwrite the original file, use something like:
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
sedis part of a script, The Unix Way™ would (IMHO) be to usesednon-destructively, test that it exited cleanly, and only then remove the extraneous file.