Shell – sed insert in the beginning of multiple files is not working

sedshell-script

I came across a lot of answers, including theses:

And I can't find a way to do what I want to do. I need to insert #encoding:utf-8 at the beginning of every .html.erb file of my directory (recursively). I tried using this command

find . -iname "*.erb" -type f -exec sed -ie "1i \#encoding:utf-8" {} \;

But it throws this error:

sed: 1: "1i #encoding:utf-8": extra characters after \ at the end of i command

Best Answer

To edit file in-place with OSX sed, you need to set empty extension:

$ sed -i '' '1i\
#encoding:utf-8' filename

And you need a literal newline after i\. This is specified by POSIX sed.

Only GNU sed allows text to be inserted on the same line with command.

sed can also works with multiple files at once, so you can use -exec command {} + form:

$ find . -iname "*.erb" -type f -exec sed -i '' '1i\
#encoding:utf-8' {} +
Related Question