Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed command with -i option failing on Mac, but works on Linux

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' * 
like image 928
Yarin Avatar asked Nov 22 '10 15:11

Yarin


People also ask

Does sed work on Mac?

One way to make the GNU version of the SED to work on the Mac OS X, is to directly install the gnu-sed along with the default names which will assure you that you won't have to run different commands on both the operating systems.

Does sed work on Linux?

The SED command in Linux stands for Stream EDitor and is helpful for a myriad of frequently needed operations in text files and streams. Sed helps in operations like selecting the text, substituting text, modifying an original file, adding lines to text, or deleting lines from the text.

What does `- E option in sed do?

The -e tells sed to execute the next command line argument as sed program. Since sed programs often contain regular expressions, they will often contain characters that your shell interprets, so you should get used to put all sed programs in single quotes so your shell won't interpret the sed program.


1 Answers

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 it 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

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.

E.g., perl -i -pe's/old_link/new_link/g' *

like image 96
Sinetris Avatar answered Sep 25 '22 20:09

Sinetris