Hello, i’m working with ruby 1.8.5 on a Suse SLES 9 Linux machine.
I need to replace strings inside files, specifically the string
FECHAIMPRE
with the current date. I had a bash script that looked like this:
BOF#################################################################
date=date '+%d:%m:%y'
for item in ls /u/sag/impresion/PRODISAA/etiquetas/lpt28*.tmp
do
sed -e s/FECHAIMPRE/$date/g < $item > $item.po
mv $item.po $item
done
EOF#################################################################
And i wanted to rewrite it in ruby. I came up with this:
#BOF#################################################################
$fecha= Time.now.strftime("%d/%m/%Y")
def UpdateDates(file)
filename= file.to_s
# Rename "file" to "file.temp"
FileUtils.mv(filename, filename + ".temp")
# Create "file" file
File.open(filename, "w") do |out|
# Write in "file" the modified "file.temp" lines.
IO.foreach(filename + ".temp") do |line|
if line =~ /FECHAIMPRE/
line.gsub!(/FECHAIMPRE/, $fecha)
end
out << line
end
end
# Erase the temporal
FileUtils.rm(filename + ".temp", :force => true)
end
Dir.glob("*.tmp").each { |file| UpdateDates(file) }
#EOF#################################################################
But i keep thinking there has to be a shorter way. I read the ruby
documentation
for IO and File classes but i haven’t found any better solution.
What do you think about it???
Thanks!