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

  • You should process step by step. First make sure your sed command is ok, then combine it with the find command. – Martin Delille Apr 20 '15 at 8:47

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' {} +
  • is the new line intentional? – Thomas Ayoub Apr 20 '15 at 9:15
  • 1
    @Thomas: yes, it's specified by POSIX. You can read the link I gave in my answer. – cuonglm Apr 20 '15 at 9:16

You can use Vim in Ex mode:

ex -sc '1i|#encoding:utf-8' -cx file
  1. 1 select line 1

  2. i insert text and newline

  3. x save and close


Here are a few ways of doing what you want:

  1. sed

    find . -iname "*.erb" -type f -exec \
     sed -i '' '1s/^/#encoding:utf-8\n/' {} \;

    I don't have access to a BSD sed to check, so I can't guarantee that the \n will be read correctly. Try the command on a single file and without the -i first to make sure.

  2. Perl

    find . -iname "*.erb" -type f -exec \
        perl -i -pe 'print "#encoding:utf-8\n" if $.==1;' {} \;
  3. shell

    find . -iname "*.erb" -type f -exec \
        sh -c 'echo "#encoding:utf-8" >tmp && cat "$1" >> tmp && mv tmp "$1"' sh {} \;

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.