4

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

3 Answers3

6

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' {} +
cuonglm
  • 153,898
2

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

Zombo
  • 1
  • 5
  • 44
  • 63
1

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 {} \;
    
Kusalananda
  • 333,661
terdon
  • 242,166