在 OS X 上使用 sed 进行就地编辑 [英] In-place edits with sed on OS X

查看:26
本文介绍了在 OS X 上使用 sed 进行就地编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 OS X 上使用 sed 编辑文件.我使用以下命令:

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

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

输出被发送到终端.file.txt 未修改.使用以下命令将更改保存到 file2.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

但是我不想要另一个文件.我只想编辑file1.txt.我该怎么做?

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

我试过 -i 标志.这会导致以下错误:

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

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

推荐答案

您可以正确使用 -i 标志,方法是为其提供后缀以添加到备份文件中.扩展您的示例:

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

将为您提供两个文件:一个名为 file1.txt 的文件包含替换内容,另一个名为 file1.txt.bu 的文件包含原始内容.

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.

轻度危险

如果您想破坏性地覆盖原始文件,请使用以下内容:

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.

除了可能会毁掉你的原作之外,我不知道以这种方式欺骗 sed 有任何进一步的危险.然而,应该注意的是,如果 sed 的这种调用是脚本的一部分,Unix Way™ 将(恕我直言)非破坏性地使用 sed,测试它干净地退出,然后才删除无关的文件.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆