thisiscrazy4
thisiscrazy4

Reputation: 1965

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?

Upvotes: 5

Views: 14739

Answers (5)

Vulwsztyn
Vulwsztyn

Reputation: 2261

You can do this by invoking sed in your shell, given that you are in the unix env:

sed -i -E "s-<appId>[0-9]+</appId>-<appId>123</appId>-g" a.xml

where a.xml is your filename

Upvotes: 0

Steve Benner
Steve Benner

Reputation: 1717

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
)

Upvotes: 6

knut
knut

Reputation: 27845

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)

Upvotes: 15

ghostdog74
ghostdog74

Reputation: 342303

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

Upvotes: 2

Ray Toal
Ray Toal

Reputation: 88378

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.

Upvotes: 1

Related Questions