在文件中的特定字符串后附加内容?

时间:2010-09-11 02:23:36

标签: ruby

我有这个文件:

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

我想补充一下:

My number is Baz.

后:

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

结果将是:

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

我怎么能在Ruby中做到这一点?

1 个答案:

答案 0 :(得分:1)

我确信有人可以发布一个更惯用的版本,但是

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