Ruby:如何替换文件中的文本? [英] Ruby: How to replace text in a file?

查看:82
本文介绍了Ruby:如何替换文件中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是xml文件中的一行:

The following code is a line in an xml file:

<appId>455360226</appId>

如何使用 ruby​​ 用另一个数字替换 2 个标签之间的数字?

How can I replace the number between the 2 tags with another number using ruby?

推荐答案

不可能一步修改文件内容(至少我不知道,当文件大小发生变化时).您必须读取该文件并将修改后的文本存储在另一个文件中.

There is no possibility to modify a file content in one step (at least none I know, when the file size would change). You have to read the file and store the modified text in another file.

replace="100"
infile = "xmlfile_in"
outfile = "xmlfile_out"
File.open(outfile, 'w') do |out|
  out << File.open(infile).read.gsub(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
end  

或者您将文件内容读入内存,然后用修改后的内容覆盖文件:

Or you read the file content to memory and afterwords you overwrite the file with the modified content:

replace="100"
filename = "xmlfile_in"
outdata = File.read(filename).gsub(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")

File.open(filename, 'w') do |out|
  out << outdata
end  

(希望有效,代码未测试)

(Hope it works, the code is not tested)

这篇关于Ruby:如何替换文件中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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