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
This creates backup files. E.g.
sed -i -e 's/hello/hello world/' testfile
for me, creates a backup file, testfile-e, in the same dir.I've similar problem with MacOS
doesn't works, but
works well.
You can use
-i''
(--in-place
) forsed
as already suggested. See: The-i
in-place argument, however note that-i
option is non-standard FreeBSD extensions and may not be available on other operating systems. Secondlysed
is a Stream EDitor, not a file editor.Alternative way is to use built-in substitution in Vim Ex mode, like:
and for multiple-files:
To edit all files recursively you can use
**/*.*
if shell supports that (enable byshopt -s globstar
).Another way is to use
gawk
and its new "inplace" extension such as:You can use the -i flag 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.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:
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 usesed
non-destructively, test that it exited cleanly, and only then remove the extraneous file.you can use,
sed -i -e 's///'
example, sed -i -e 's/Hello/Bye/' file.txt
this works flawless in mac