In-place edits with sed on OS X

2019-01-03 12:21发布

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

6条回答
甜甜的少女心
2楼-- · 2019-01-03 12:45
sed -i -- "s/https/http/g" file.txt
查看更多
姐就是有狂的资本
3楼-- · 2019-01-03 12:46

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.

查看更多
够拽才男人
4楼-- · 2019-01-03 12:58

I've similar problem with MacOS

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

doesn't works, but

sed -i"any_symbol" 's/oldword/newword/' file1.txt

works well.

查看更多
Ridiculous、
5楼-- · 2019-01-03 13:05

You can use -i'' (--in-place) for sed 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. Secondly sed is a Stream EDitor, not a file editor.


Alternative way is to use built-in substitution in Vim Ex mode, like:

$ ex +%s/foo/bar/g -scwq file.txt

and for multiple-files:

$ ex +'bufdo!%s/foo/bar/g' -scxa *.*

To edit all files recursively you can use **/*.* if shell supports that (enable by shopt -s globstar).


Another way is to use gawk and its new "inplace" extension such as:

$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1
查看更多
欢心
6楼-- · 2019-01-03 13:06

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.

查看更多
7楼-- · 2019-01-03 13:07

you can use,

sed -i -e 's///'

example, sed -i -e 's/Hello/Bye/' file.txt

this works flawless in mac

查看更多
登录 后发表回答