你可以写在一个文件的中间,但你必须小心,以保持字符串的长度覆盖相同,否则你会覆盖下面的一些文本。我在这里使用File.seek给出了一个例子,IO :: SEEK_CUR给出了文件指针的当前位置,在刚刚读取的行的末尾,+1表示行末尾的CR字符。
look_for = "bbb"
replace_with = "xxxxx"
File.open(DATA, 'r+') do |file|
file.each_line do |line|
if (line[look_for])
file.seek(-(line.length + 1), IO::SEEK_CUR)
file.write line.gsub(look_for, replace_with)
end
end
end
__END__
aaabbb
bbbcccddd
dddeee
eee
执行后,在脚本结尾处,您现在有以下内容,而不是您想到的内容。
aaaxxxxx
bcccddd
dddeee
eee
考虑到这一点,使用这种技术的速度比经典的“读取和写入新文件”方法要好得多。 在音乐数据大小为1.7 GB的文件上查看这些基准。 对于经典的方法,我使用了韦恩的技术。 基准测试是通过.bmbm方法完成的,因此文件的缓存功能没有什么大不了的。在Windows 7上使用MRI Ruby 2.3.0完成测试。 字符串被有效替换,我检查了两种方法。
require 'benchmark'
require 'tempfile'
require 'fileutils'
look_for = "Melissa Etheridge"
replace_with = "Malissa Etheridge"
very_big_file = 'D:\Documents\muziekinfo\all.txt'.gsub('\\','/')
def replace_with file_path, look_for, replace_with
File.open(file_path, 'r+') do |file|
file.each_line do |line|
if (line[look_for])
file.seek(-(line.length + 1), IO::SEEK_CUR)
file.write line.gsub(look_for, replace_with)
end
end
end
end
def replace_with_classic path, look_for, replace_with
temp_file = Tempfile.new('foo')
File.foreach(path) do |line|
if (line[look_for])
temp_file.write line.gsub(look_for, replace_with)
else
temp_file.write line
end
end
temp_file.close
FileUtils.mv(temp_file.path, path)
ensure
temp_file.close
temp_file.unlink
end
Benchmark.bmbm do |x|
x.report("adapt ") { 1.times {replace_with very_big_file, look_for, replace_with}}
x.report("restore ") { 1.times {replace_with very_big_file, replace_with, look_for}}
x.report("classic adapt ") { 1.times {replace_with_classic very_big_file, look_for, replace_with}}
x.report("classic restore") { 1.times {replace_with_classic very_big_file, replace_with, look_for}}
end
这给了
Rehearsal ---------------------------------------------------
adapt 6.989000 0.811000 7.800000 ( 7.800598)
restore 7.192000 0.562000 7.754000 ( 7.774481)
classic adapt 14.320000 9.438000 23.758000 (32.507433)
classic restore 14.259000 9.469000 23.728000 (34.128093)
----------------------------------------- total: 63.040000sec
user system total real
adapt 7.114000 0.718000 7.832000 ( 8.639864)
restore 6.942000 0.858000 7.800000 ( 8.117839)
classic adapt 14.430000 9.485000 23.915000 (32.195298)
classic restore 14.695000 9.360000 24.055000 (33.709054)
所以in_file中更换了快4倍。
如果您的代码要读取然后覆盖会导致进程中途失败,请考虑结果:您会冒着破坏文件的风险。 – 2010-12-10 00:29:49
好吧,作为后续问题:从命令行,你可以这样做:ruby -pe“gsub(/ blah /,'newstuff')”whatev.txt。这就是我想要做的,但我不想在命令行上这样做,我想把它放在更大的东西里面。任何人都可以在内部告诉我,那个命令正在做什么,从而给出了逐行编辑文件的错觉?它是写入临时文件还是使用数组?因为它似乎很快处理相当大的文件,而不是迄今为止提供的建议。 – Hsiu 2010-12-10 08:42:08
这是一个很好的问题。你能把它变成一个新的问题吗?这使得其他人更容易看到并回答它。另外,如果这个问题得到了您的满意答复,您能否接受该答案?谢谢! – 2010-12-16 23:20:58