0

I'm trying to use this as my starting guide for using sed to add a line to a file in OSX. https://stackoverflow.com/questions/25631989/sed-insert-line-command-osx

sed -i '.json' '2i\
this is a test place
    ' dummy.txt

The above works. But I need to do expansion so I'm starting with something simple by just replacing with double quotes like

sed -i '.json' "2i\
this is a test place
    " dummy.txt

Why do I get command i expects \ followed by text? Or how do I use double quotes on Mac to add text to a specific line?

  • @steeldriver can you put that as the answer so i can mark it as answered. thank you! – Crystal Oct 25 '18 at 19:12
3
$ sed "2i\\
These are words on\\
multiple lines\\
" input
1
These are words on
multiple lines
2
3
4
5
6
7
8
9
10

You need to escape the backslash so that sed gets to parse it and escape the literal linefeed you're trying to escape for sed rather than the shell.

$ sed '2i\
thing' input

With the strong quotes, everything is passed literally, so sed sees <2> <i> <literal linefeed>

$ sed "2i\
thing" input

With the weak quotes, the shell gets first dibs at parsing the string, and so sed sees <2> <i> <linefeed>, which is a syntax error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.