在Ruby中查找并替换文件

我有这个用ruby编写的小程序。 我在SO上发现了一段很好的代码,用于查找和替换文件中的某些内容,但它似乎不起作用。 这是代码:

#!/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) } 

谢谢大家 !

我跳过你做的检查,看看这条线是否已经存在,并且通常是这样的(这里我想用’BAR’替换’FOO’):

 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的使用在expand_path也可能有点迂腐,但我喜欢它,所以我不会意外地破坏一些我不是故意的文件。