带有 -i 选项的 sed 命令在 Mac 上失败,但适用于 Linux [英] sed command with -i option failing on Mac, but works on Linux

查看:37
本文介绍了带有 -i 选项的 sed 命令在 Mac 上失败,但适用于 Linux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已成功使用以下 sed 命令在 Linux 中搜索/替换文本:

I've successfully used the following sed command to search/replace text in Linux:

sed -i 's/old_link/new_link/g' *

但是,当我在 Mac OS X 上尝试时,我得到:

However, when I try it on my Mac OS X, I get:

命令 c 需要 后跟文本"

"command c expects followed by text"

我以为我的 Mac 运行的是普通的 BASH shell.怎么了?

I thought my Mac runs a normal BASH shell. What's up?

根据@High Performance,这是由于 Mac sed 具有不同的 (BSD) 风格,因此我的问题是如何在 BSD sed<中复制此命令/代码>?

According to @High Performance, this is due to Mac sed being of a different (BSD) flavor, so my question would therefore be how do I replicate this command in BSD sed?

这是导致这种情况的实际示例:

Here is an actual example that causes this:

sed -i 's/hello/gbye/g' *

推荐答案

如果您使用 -i 选项,您需要为您的备份提供扩展名.

If you use the -i option you need to provide an extension for your backups.

如果你有:

File1.txt
File2.cfg

命令(注意 -i''-e 之间缺少空格,以使其适用于新版本的Mac 和 GNU):

The command (note the lack of space between -i and '' and the -e to make it work on new versions of Mac and on GNU):

sed -i'.original' -e 's/old_link/new_link/g' *

创建 2 个备份文件,例如:

Create 2 backup files like:

File1.txt.original
File2.cfg.original

没有可移植的方法来避免制作备份文件,因为不可能找到适用于所有情况的混合 sed 命令:

There is no portable way to avoid making backup files because it is impossible to find a mix of sed commands that works on all cases:

  • sed -i -e ... - 在 OS X 上不起作用,因为它会创建 -e 备份
  • sed -i'' -e ... - 不适用于 OS X 10.6,但适用于 10.9+
  • sed -i '' -e ... - 不适用于 GNU
  • sed -i -e ... - does not work on OS X as it creates -e backups
  • sed -i'' -e ... - does not work on OS X 10.6 but works on 10.9+
  • sed -i '' -e ... - not working on GNU

注意鉴于没有适用于所有平台的 sed 命令,您可以尝试使用另一个命令来获得相同的结果.

Note Given that there isn't a sed command working on all platforms, you can try to use another command to achieve the same result.

例如,perl -i -pe's/old_link/new_link/g' *

这篇关于带有 -i 选项的 sed 命令在 Mac 上失败,但适用于 Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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