Insert a line into a file using rail patterns

I am trying to create a rail template that will add code to files in specific line numbers. For example, I need to add a route to config / routes.rb

I tried sed, gsed (only the reason I am on mac and they say sed has problems with insert and add), in any case, I could not achieve the desired result.

Any help on this would be greatly appreciated.

I tried a few permutations of this command, but nobody is working, here is an example

run "gsed '3 a/This is it' config/routes.rb" 

maybe another suggestion

EDIT ::

ok I took a break, and when I returned, after reading sed, I realized that I needed to write the stream back to the file, but I did it before,

 run "gsed '2 a\ Add this line after 2nd line ' config/routes.rb > config/routes.rb" 

but the routes file will be empty, so I tried using a different file name (new.routes.rb)

 run "gsed '2 a\ Add this line after 2nd line ' config/routes.rb > config/new.routes.rb" 

and it worked, so I know what to do now.

+4
source share
3 answers

Since line numbers change as your file grows, it’s best to insert new code before or after existing string expressions. Inside the template generator, you can do something like this:

 inject_into_file 'config/application.rb', :before => " end" do "\n config.logger = Logger.new(config.paths.log.first, 50, 1048576)\n\n" end 

Note. You can use: after if: before does not meet your needs.

+15
source

I need to wonder why you are using sed for this. Write a Ruby script to open the file, read it line by line, make changes and write the file back. The only problem you are about to encounter is editing the file in place. To work around this, open a temporary file , write to this file, and then move this file over the old file using File.move.

0
source

this will help, just remember to delete the old one and rename the new one in its place

 run "gsed '2 a\ Add this line after 2nd line ' config/routes.rb > config/new.routes.rb" 
0
source

All Articles