Search and replace in files

Hi,

I found this commande line online to find and replace in file:
ruby -i.bkp -pe “gsub(/search/, ‘replace’)” *.gemspec

This line has to be ran in the terminal, is it possible to execute this
line from a ruby file?

Greg

Gregory Ma wrote in post #1009603:

I found this commande line online to find and replace in file:
ruby -i.bkp -pe “gsub(/search/, ‘replace’)” *.gemspec

This line has to be ran in the terminal, is it possible to execute this
line from a ruby file?

Trivially:

system("ruby -i.bkp ...etc")

Otherwise, you can replicate the functionality yourself. Here’s a
starting point (untested):

files = Dir["*.gemspec"]
files.each do |fn|
File.open(fn) do |i|
File.open("#{fn}.new", “w”) do |o|
i.each_line do |line|
o.puts line.gsub(/search/, ‘replace’)
end
end
end
File.rename(fn, “#{fn}.bkp”)
File.rename("#{fn}.new", fn)
end

If this works, refactor it a bit to make it more useful:

def process_files(files)
files.each do |fn|
File.open(fn) do |i|
File.open("#{fn}.new", “w”) do |o|
i.each_line do |line|
yield line,o
end
end
end
File.rename(fn, “#{fn}.bkp”)
File.rename("#{fn}.new", fn)
end
end

process_files(Dir["*.gemspec"]) do |line,out|
out << line.gsub(/search/, ‘replace’)
end