Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 576
thisiscrazy4 Avatar asked Sep 03 '11 02:09

thisiscrazy4


3 Answers

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)

like image 171
knut Avatar answered Sep 17 '22 10:09

knut


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
)
like image 26
Steve Benner Avatar answered Sep 20 '22 10:09

Steve Benner


replace="100"
File.open("xmlfile").each do |line|
  if line[/<appId>/ ]
     line.sub!(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
  end
  puts line
end
like image 32
ghostdog74 Avatar answered Sep 18 '22 10:09

ghostdog74