开发者

Ruby: How to replace text in a file?

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开发者_StackOverflow中文版?


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)


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
)


replace="100"
File.open("xmlfile").each do |line|
  if line[/<appId>/ ]
     line.sub!(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
  end
  puts line
end


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜