sed command with -i option failing on Mac, but wor

2018-12-31 09:46发布

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

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

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

"command c expects \ followed by text"

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

EDIT:

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?

EDIT:

Here is an actual example that causes this:

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

11条回答
裙下三千臣
2楼-- · 2018-12-31 10:27
sed -ie 's/old_link/new_link/g' *

Works on both BSD & Linux

查看更多
伤终究还是伤i
3楼-- · 2018-12-31 10:30

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

If you have:

File1.txt
File2.cfg

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' *

create 2 backup files like:

File1.txt.original
File2.cfg.original

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

  • 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
查看更多
公子世无双
4楼-- · 2018-12-31 10:30

I believe on OS X when you use -i an extension for the backup files is required. Try:

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

Using GNU sed the extension is optional.

查看更多
浅入江南
5楼-- · 2018-12-31 10:33

Your Mac does indeed run a BASH shell, but this is more a question of which implementation of sed you are dealing with. On a Mac sed comes from BSD and is subtly different from the sed you might find on a typical Linux box. I suggest you man sed.

查看更多
怪性笑人.
6楼-- · 2018-12-31 10:37

This works with both GNU and BSD versions of sed:

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

or with backup:

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

Note missing space after -i option! (Necessary for GNU sed)

查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 10:37

As the other answers indicate, there is not a way to use sed portably across OS X and Linux without making backup files. So, I instead used this Ruby one-liner to do so:

ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml

In my case, I needed to call it from a rake task (i.e., inside a Ruby script), so I used this additional level of quoting:

sh %q{ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml}
查看更多
登录 后发表回答