2011-08-02 136 views
4

我有这个用Ruby编写的小程序。我在这里发现了一段很好的代码,用于查找和替换文件中的某些内容,但似乎并不奏效。 这里是代码:查找并替换Ruby中的文件

#!/usr/bin/env ruby 

DOC = "test.txt" 
FIND = /,,^M/ 
SEP = "\n" 

#make substitution 
File.read(DOC).gsub(FIND, SEP) 

#Check if the line already exist 
unique_lines = File.readlines(DOC).uniq 

#Save the result in a new file 
File.open('test2.txt', 'w') { |f| f.puts(unique_lines) } 

谢谢大家!

回答

8

我跳到你做,看看行已经存在,并且通常是这样的(在这里我想用“BAR”,以取代“富”)去检查:

full_path_to_read = File.expand_path('~/test1.txt') 
full_path_to_write = File.expand_path('~/test2.txt') 

File.open(full_path_to_read) do |source_file| 
    contents = source_file.read 
    contents.gsub!(/FOO/, 'BAR') 
    File.open(full_path_to_write, "w+") { |f| f.write(contents) } 
end 

采用expand_path在这里也可能有些迂腐,但我喜欢它,所以我不会不小心打破我不想要的某个文件。