never_had_a_name
never_had_a_name

Reputation: 93206

Append content after a specific string in a file?

I have this file:

# file.txt
My first name is Foo
and my last name is Bar.
I live in Baz.

I want to add:

My number is Baz.

after:

My first name is Foo
and my last name is Bar.

So the result will be:

My first name is Foo
and my last name is Bar.
My number is Baz.
I live in Baz.

How could I do this in Ruby?

Upvotes: 1

Views: 272

Answers (1)

Steve B.
Steve B.

Reputation: 57304

I'm sure someone can post a more idiomatic version, but

tmp=File.open('temp','w')
File.open(file, 'r') do |f|
   while line=f.gets
     tmp.write(line)
     tmp.write(value) if line == "value to match"
  end
end
tmp.close

Upvotes: 1

Related Questions