ruby – 为什么不gsub!改变我的文件?
我正在尝试对目录中的所有文本文件进行简单的查找/替换,修改[RAVEN_START的任何实例:通过在行之前插入一个字符串(在本例中为“raven was here”).
这是整个ruby程序: #!/usr/bin/env ruby require 'rubygems' require 'fileutils' #for FileUtils.mv('your file','new location') class RavenParser rawDir = Dir.glob("*.txt") count = 0 rawDir.each do |ravFile| #we have selected every text file,so now we have to search through the file #and make the needed changes. rav = File.open(ravFile,"r+") do |modRav| #Now we've opened the file,and we need to do the operations. if modRav lines = File.open(modRav).readlines lines.each { |line| if line.match /[RAVEN_START:.*]/ line.gsub!(/[RAVEN_START:/,'raven was here '+line) count = count + 1 end } printf("Total Changed: %dn",count) else printf("No txt files found. n") end end #end of file replacing instructions. end # S end 程序运行并编译正常,但是当我打开文本文件时,文件中的任何文本都没有变化.正确计数增量(即,它等于[RAVEN_START:跨所有文件的实例数],但实际替换未能发生(或至少不保存更改). 我的语法是在gsub上!不正确的?我做错了什么吗? 解决方法
您正在读取数据,更新数据,然后忽略将数据写回文件.你需要这样的东西:
# And save the modified lines. File.open(modRav,'w') { |f| f.puts lines.join("n") } 紧接在此之前或之后: printf("Total Changed: %dn",count) 正如下面的DMG注释,只是覆盖文件不是正确的偏执,因为你可能会在写入过程中被中断并丢失数据.如果你想成为偏执狂(我们所有人都应该是因为他们真的想要我们),那么你想写一个temporary file然后做一个原子重命名来替换原来的新文件.重命名通常仅在您保留在单个文件系统中时才起作用,因为无法保证OS的临时目录(默认情况下Tempfile使用)与modRav位于同一文件系统上,因此 modRavDir = File.dirname(File.realpath(modRav)) tmp = Tempfile.new(modRav,modRavDir) tmp.write(lines.join("n")) tmp.close File.rename(tmp.path,modRav) 您可能希望将其粘贴在单独的方法(也许是safe_save(modRav,lines))中,以避免进一步混乱您的块. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |