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

1
  • You should process step by step. First make sure your sed command is ok, then combine it with the find command. Commented Apr 20, 2015 at 8:47

3 Answers 3

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

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 {} \;
    

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .