Adding a TeX macro to the beginning of a file using sed (why doesn’t the method work?)

sedtext processing

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.

Best Answer

I don't have access to sed right now, so I'm not entirely sure this is correct, but I think you just need to remove the first backslash and the space following it.

sed -i '1i\\\def\\\submit{}' 'dirname/filename'

Try it and see if that works.

Related Question