如何搜索一个模式的文件文本,并将其替换为给定的值 [英] How to search file text for a pattern and replace it with a given value

查看:77
本文介绍了如何搜索一个模式的文件文本,并将其替换为给定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



想法?

解决方案



  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)

#仅仅打印文件内容, :
puts new_contents

#要将更改写入文件,请使用:
File.open(file_name,w){| file | file.puts new_contents}
end


I'm looking for a script to search a file (or list of files) for a pattern and, if found, replace that pattern with a given value.

Thoughts?

解决方案

Here's a quick short way to do it.

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

这篇关于如何搜索一个模式的文件文本,并将其替换为给定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆