我有这个文件:
# 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中做到这一点?
答案 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