在OS X上就地编辑sed [英] In-place edits with sed on OS X
问题描述
$ b
sed' 我想用OS X上的sed编辑一个文件。 s / oldword / newword /'file.txt
输出发送到终端。没有修改 file.txt 。使用以下命令将更改保存到 file2.txt :
sed's / oldword / newword /'file1.txt> file2.txt
但是我不想要另一个文件。我只想编辑 file1.txt 。我怎样才能做到这一点?
我尝试了-i标志。这会导致以下错误:
sed:1:file1.txt:无效的命令代码f
您可以通过提供后缀来正确使用-i标志到备份文件。扩展你的例子:
sed -i.bu's / oldword / newword /'file1.txt
code>
会给你两个文件:一个名为file1.txt,包含替换,另一个名为file1.txt。有原始内容的。如果您想破坏性地覆盖原始文件,请使用 例如:
sed -i''s / oldword / newword /'file1.txt
^ note空间
由于线被解析的方式,选项标志和参数之间需要一个空格因为参数是零长度的。
除了可能摧毁你的原始文件,我不知道任何进一步的欺骗性的危险办法。但是,应该注意的是,如果 sed
的调用是脚本的一部分,那么Unix Way™(恕我直言)将使用 sed
非破坏性地测试它是否干净地退出,然后才删除无关的文件。
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 -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.
这篇关于在OS X上就地编辑sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!