Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed insert line command OSX

I'm trying to insert text to the third line in a file using sed, and the syntax I've found on other forums is:

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

When I use this however, I get an error:

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

I can't seem to figure out what is causing the problem. I'm using OSX, which is why I have an empty ' ' as my extension.

Thanks!

like image 684
gdavtor Avatar asked Sep 02 '14 20:09

gdavtor


People also ask

How do you insert a line in a sed command?

We've learned that sed's “a” and “i” commands can insert or append a new line. The backslash character after the “a” or “i” command doesn't function as the part of an escape sequence, such as \t as a tab or \n as a newline. Instead, it indicates the beginning of the text in the new line we're inserting.

Does sed command 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.

How do I add a new line in Mac?

Press option + return or control + return to enter a new line.

What is sed command in Mac?

SED is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits, SED works by making only one pass over the input(s), and is consequently more efficient.


1 Answers

You should put a newline directly after the \:

sed '3i\ text to insert' file 

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


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

sed "3i\\ text to insert" file 

This is because a double-quoted string is processed first by the shell, and \ followed by a newline is removed:

$ echo "abc\ def" abcdef 
like image 60
Tom Fenech Avatar answered Oct 01 '22 20:10

Tom Fenech