Ruby – 打开文件,查找并替换多行

我是ruby的新手,希望有人可以帮我弄清楚如何打开文件,然后使用gsub查找并替换多个条件。

这是我到目前为止所得到的,但这似乎不起作用,因为第二个替换var覆盖了第一个:

text = File.read(filepath) replace = text.gsub(/aaa/, "Replaced aaa with 111") replace = text.gsub(/bbb/, "Replace bbb with 222") File.open(filepath, "w") {|file| file.puts replace} 

将第三行更改为

 replace = replace.gsub(/bbb/, "Replace bbb with 222") 

你每次都要从原来的“文本”中取代,第二行需要替换替换:

 replace = replace.gsub(/bbb/, "Replace bbb with 222") 

有趣的是,如果您不想重新扫描数据,请使用gsub的块forms:

 replace = text.gsub(/(aaa|bbb)/) do |match| case match when 'aaa': 'Replaced aaa with 111' when 'bbb': 'Replace bbb with 222' end end 

这可能不是最有效的做事方式,但这是看待问题的另一种方式。 如果性能对您很重要,那么值得对两种方式进

我可能会像这样写它…

 #!/usr/bin/env ruby filepath = '/tmp/test.txt' File.open filepath, 'w' do |f| $<.each_line do |line| f.puts line.gsub(/aaa/, 'Replaced aaa with 111').gsub /bbb/, 'Replace bbb with 222' end end 

这是一个class轮

 IO.write(filepath, File.open(filepath) {|f| f.read.gsub(/aaa|bbb/) {|m| (m.eql? 'aaa') '111' : '222'}}) 

IO.write默认截断给定文件,因此如果您首先读取文本,请执行regex File.open在块模式下使用File.open返回结果字符串,它将替换文件的内容。 漂亮吧?

它也适用于多行:

 IO.write(filepath, File.open(filepath) do |f| f.read.gsub(/aaa|bbb/) do |m| (m.eql? 'aaa') '111' : '222' end end )