2

I have file named user.rb as like:

class User < ApplicationRecord end 

I want to add a new line and after adding line it will look :

class User < ApplicationRecord include Company end 

But I want to add this additional line from bash script or terminal. I tried it with this bash code:

sed -i '' 's/end/include Company\n\end/' app/models/user.rb 

But it does not return new line after adding line. Please help me.

2 Answers 2

3

With sed, append (a) the desired portion after match (here i am matching < ApplicationRecord at the end of the line):

sed '/<[[:blank:]]*ApplicationRecord$/a\ include Company' file.rb 

To edit the file in-place with original one backed up with a .bak extension:

sed -i.bak '/<[[:blank:]]*ApplicationRecord$/a\ include Company' file.rb 

Without any backup:

sed -i '' '/<[[:blank:]]*ApplicationRecord$/a\ include Company' file.rb 

Example:

$ cat file.rb class User < ApplicationRecord end $ sed '/<[[:blank:]]*ApplicationRecord$/a\ include Company' file.rb class User < ApplicationRecord include Company end 
Sign up to request clarification or add additional context in comments.

Comments

1

On OSX you can use this sed command:

sed -i.bak '/ApplicationRecord$/,/^end$/{/end$/i\ include Company }' file 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.