I need to add a line to the beginning of a file. The line in question is
\def\submit{}
I've got a semi-working solution using sed
. I don't know sed
, but got it from somewhere on the net, but it doesn't work quite right, because it inserts an unwanted space at the beginning of the line. While this doesn't really matter, I figure I might as well do this right.
sed -i '1i\ \\\def\\\submit{}' 'dirname/filename'
It seems from my reading that all those extra backslashes are required to escape the shell. Other solutions are also welcome, but I'd like a comparably compact one liner if possible. Thanks.
This question, Inserting text at the beginning of a file with sed via the terminal in Linux is similar, but doesn't help me debug my expression.
EDIT: I've accepted @Jonathan's answer, because it explains what was wrong with my previous approach. However, I've also added an answer.
1i
you need GNUsed
. And unless you want a leading space on the first line, thesed
command should be:1i\\\def\\submit{}
. The first backslash needs to be tripled because the first backslash character is actually part of the command name, which isi\
. – peterph Jan 18 '14 at 23:39sed -i '1i\\\def\\submit{}\' 'dir1/foo'
. Feel free to submit your own solution. I got\\def\\submit{}
. – Faheem Mitha Jan 19 '14 at 15:571i\\\def\\submit{}
, you tried1i\\\def\\submit{}\
- don't be surprised you got different result. – peterph Jan 19 '14 at 20:02submit
, which however, doesn't make any difference to the result - both versions work. I guess I should stop cargo-culting and understand what sed actually does. – Faheem Mitha Jan 19 '14 at 20:52