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!
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.
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.
Press option + return or control + return to enter a new line.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With