Sed insert line OSX command

I am trying to insert text into the third line in a file using sed, and the syntax I found in other forums is:

sed -i '' "3i\ text to insert" file 

When I use this, I get an error message:

 sed: 1: "3i\ text to insert": extra characters after \ at the end of i command 

I can not understand what is causing the problem. I use OSX, so I have an empty "as extension".

Thanks!

+11
source share
6 answers

You should put a new line immediately after \ :

 sed '3i\ text to insert' file 

This is actually the behavior defined in the POSIX specification. The fact that GNU sed allows you to specify text to be inserted on one line is an extension.


If for any reason you need to use double quotes around the sed command, you must escape the backslash at the end of the first line:

 sed "3i\\ text to insert" file 

This is because the shell first processes the string in double quotation marks, and \ is deleted, followed by a newline character:

 $ echo "abc\ def" abcdef 
+30
source

On OSX, you can use:

 sed -i.bak '3i\ text to insert ' file 
+14
source

Here's how to do it in single line syntax

 sed -i '' -e "2s/^//p; 2s/^.*/text to insert/" file 
  • duplicate the second line: 2s/^//p;

  • replace the new line with the text: 2s/^.*/text to insert/

+4
source

It works for me

 sed -i '' '3i\ text to insert' file 
+1
source

If you want to modify a file of a specific file type (.sh in my case), use this command.

 sed -i '.sh' '3i\ mymodified text to insert' temp.sh 

Make sure you have a line break after the slash ("\")

0
source

One line for OSX using ANSI-C quoting:

 sed -i '' '3i\'$'\n''text to insert' file 

Adapted from fooobar.com/questions/146335 / ...

0
source

Source: https://habr.com/ru/post/974714/


All Articles