我試圖做一個簡單的查找/替換目錄中的所有文本文件,修改任何[RAVEN_START:
實例插入一個字符串(在這裏,'烏鴉在這裏')在行之前。爲什麼不會gsub!改變我的檔案?
這裏是整個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: %d\n",count)
else
printf("No txt files found. \n")
end
end
#end of file replacing instructions.
end
# S
end
的程序運行和編譯罰款,但是當我打開文本文件時,出現了任何文件中的文字沒有變化。 count
正確遞增(即,它等於所有文件中[RAVEN_START:
的實例數),但實際的替換無法進行(或至少不保存更改)。
我的gsub!
語法錯誤嗎?我在做別的事嗎?
當然,如果程序在正確的地方中斷,你可能最終丟失數據這樣......這是更好地輸出到一個臨時文件,然後再移動文件回到原來的名稱。請參閱:http://ruby-doc.org/stdlib/libdoc/tempfile/rdoc/classes/Tempfile.html和http://pleac.sourceforge.net/pleac_ruby/fileaccess.html – DGM
@DGM:的確,一個臨時文件後跟原子重命名將是適當的偏執狂。但是,Tempfile上的重命名可能不是原子的,因爲臨時文件可能位於另一個文件系統上,因此它最終可能是文件副本而不是簡單的「rename」系統調用。因此,在構建Tempfile時,需要將'tmpdir'設置爲匹配'modRav'。我將添加一個關於完整性的更新。 –
完全正確。我知道那裏有知識,但我沒有提出任何更好的睡眠方面的鏈接。但是這個小例程**應該是編程世界的常識。如果不是,它需要更多的曝光。 :) – DGM