在Ruby中查找并替换文件

Sim*_*mon 4 ruby replace file

我有这个用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) }
Run Code Online (Sandbox Code Playgroud)

谢谢大家 !

Chr*_*nch 8

我跳过你做的检查,看看这条线是否已经存在,并且通常是这样的(这里我想用'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
Run Code Online (Sandbox Code Playgroud)

在这里使用expand_path也可能有点迂腐,但我喜欢它,以便我不会意外地破坏一些我不是故意的文件.