如何在文件文本中搜索模式并将其替换为给定值 [英] How to search file text for a pattern and replace it with a given value
本文介绍了如何在文件文本中搜索模式并将其替换为给定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一个脚本来搜索文件(或文件列表)中的某个模式,如果找到,则用给定的值替换该模式.
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.
想法?
推荐答案
免责声明: 这种方法是对 Ruby 功能的幼稚说明,而不是用于替换字符串的生产级解决方案文件.它容易出现各种故障情况,例如在崩溃、中断或磁盘已满的情况下数据丢失.此代码不适用于备份所有数据的快速一次性脚本之外的任何内容.因此,请勿将此代码复制到您的程序中.
这里有一个简单快捷的方法.
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屋!
查看全文