The difference between sed command under mac and linux


Foreword
There is a certain difference between using the sed command on Mac and Linux. The main reason is that the backup format must be specified under mac, and new line insertion is required to insert under mac.

Non-ignorable backup format

# linux下success
sed -i 's/hello/world/g' hello.text

The above line of code can be run on Linux, the role is to replace the hello found in the hello.text file with world, and directly save the modified content to the file.
If you run the above command on a Mac, you will find that this line of code will report an error. The reason is that on the Mac, when the sed command directly manipulates the file, you must specify the format of the backup, but on Linux, there is no such requirement.

# mac下success
sed -i '' 's/hello/world/g' hello.php

As shown in the above code, add a pair of quotation marks after -i to specify the backup format. If backup is not required, the contents of the quotation marks can be empty.

Insert text needs new line

sed -i '' '1i\ hello ' hello.txt

The function of the above line of code is to insert hello into the file, which can run normally under Linux, but it will still report an error on Mac.
The reason is that when you use the sed command to insert text into the file, you must insert a line break after 1i. The correct code is as follows.
For example, if you want to use this command in the terminal, the correct code is as follows, after 1i, hit enter, and then continue to enter the following commands.

sed -i '' '1i\
hello' hello.php

Because I use ruby ​​to call the shell script, I will write the command in the string, and the code to insert the text using sed in ruby ​​is as follows.

system "sed -i '' '1i\\'$'\n''hello' hello.php"

Guess you like

Origin www.cnblogs.com/xuange306/p/12702313.html