我正在寻找一个脚本来搜索文件(或文件列表)中的模式,如果找到,用给定的值替换该模式.

思想?

推荐答案

Disclaimer: This approach is a naive illustration of Ruby's capabilities, and not a production-grade solution for replacing strings in files. It's prone to various failure scenarios, such as data loss in case of a crash, interrupt, or disk being full. This code is not fit for anything beyond a quick one-off script where all the data is backed up. For that reason, do NOT copy this code into your programs.

这里有一个快速的方法.

file_names = ['foo.txt', 'bar.txt']

file_names.each do |file_name|
  text = File.read(file_name)
  new_contents = text.gsub(/search_regexp/, "replacement string")

  # To merely print the contents of the file, use:
  puts new_contents

  # To write changes to the file, use:
  File.open(file_name, "w") {|file| file.puts new_contents }
end

Ruby相关问答推荐

Ruby - 使用索引值识别和更新数组中的重复项

这个#divmod 方法输出这个结果是做什么的?

在 ruby​​ 中提取文档中的主题标签和部分

如何期望 RSpec should_receive 的一些(但不是全部)参数?

将一个目录的内容复制到另一个目录

如何判断 Capistrano 中是否存在文件(在远程服务器上)?

什么时候在 Ruby 中使用 Struct 比使用 Hash 更好?

就地修改 ruby​​ 哈希(rails strong params)

在 Rails 中,如何向 String 类添加新方法?

ActiveSupport::Memoizable 指的是哪种 Ruby memoize 模式?

如何测试数组中的所有项目是否相同?

如何让 Ruby 1.9 成为 Ubuntu 上的默认 Ruby?

判断是否在 SASS 中定义了变量

区分一个Ruby字符串或数组

将 CSV 文件转换为哈希数组

有条件的数组的第一个元素

Ruby - Array#<< 和 Array#push 之间的区别

如何计算Ruby日期的星期几?

如何判断变量是数字还是字符串?

如何在 gemspec 中指定最低 Ruby 版本?