Ruby - 打开文件,查找并替换多行 [英] Ruby - Open file, find and replace multiple lines

查看:36
本文介绍了Ruby - 打开文件,查找并替换多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to ruby and was hoping someone could help me figure out how to open a file, then using gsub to find and replace by multiple conditions.

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

Here's what I got so far but this doesn't seem to work as the 2nd replace var overrides the first:

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")

这篇关于Ruby - 打开文件,查找并替换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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