Ruby: How to replace text in a file?

2019-06-20 18:17发布

The following code is a line in an xml file:

<appId>455360226</appId>

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

4条回答
聊天终结者
2楼-- · 2019-06-20 18:35

You can do it in one line like this:

IO.write(filepath, File.open(filepath) {|f| f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)})

IO.write truncates the given file by default, so if you read the text first, perform the regex String.gsub and return the resulting string using File.open in block mode, it will replace the file's content in one fell swoop.

I like the way this reads, but it can be written in multiple lines too of course:

IO.write(filepath, File.open(filepath) do |f|
    f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)
  end
)
查看更多
Summer. ? 凉城
3楼-- · 2019-06-20 18:56

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)

查看更多
神经病院院长
4楼-- · 2019-06-20 18:56
replace="100"
File.open("xmlfile").each do |line|
  if line[/<appId>/ ]
     line.sub!(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
  end
  puts line
end
查看更多
Bombasti
5楼-- · 2019-06-20 18:56

The right way is to use an XML parsing tool, and example of which is XmlSimple.

You did tag your question with regex. If you really must do it with a regex then

s = "Blah blah <appId>455360226</appId> blah"
s.sub(/<appId>\d+<\/appId>/, "<appId>42</appId>")

is an illustration of the kind of thing you can do but shouldn't.

查看更多
登录 后发表回答