Hi,
on Windows, I need to replace some values in a file; see the program below.
1. ff
The file is in Unix fileformat; but when Ruby wrote to it, there are
DOS line endings instead of Unix one, AFAICS.
That's what I think what happens.
What I see is:
I open the file in Vim (which is ff=unix); everything looks fine. I run
the Ruby program, then Vim prompts me to relaod the file; after this,
every line ends in ^M.
When I reopen the file in Vim, everything looks OK again; I think Vim
converts the dos line endings automatically since I have
set ff=unix
in my vimrc.
I really would prefer if Ruby would only gsub the stuff I ask it to,
not the line endings.
2. gsub
How could I match a longer string, but replace only a part of it?
eg ~
string.gsub! /<(embed|object).+?width="\d+"/, "width=\"#{w}\""
... but the <object etc should stay.
3. Golf
What's a shorter / more elegant version of the program?
s.th. in the style of: grep /dimensions/, sed s/old/new/
Tobi
########################################
SVG = 'links.svg'
d = Dir.new './'
HTMLs = d.grep /^svg.*\.html$/
def get_new_dimensions
open(SVG) do |svg|
svg.read.scan \
/<svg\s+width="(.+?)"\s+height="(.+?)"/m
[($1.delete'px'),$2.delete'px']
end
end
w,h = get_new_dimensions
HTMLs.each do |html_file_name|
string = open(html_file_name) do |html_file|
html_file.read
end
# how to write these in one (gsub) line?
string.gsub! /width="\d+"/, "width=\"#{w}\""
string.gsub! /height="\d+"/, "width=\"#{h}\""
open(html_file_name,'w') do |html_file|
# changes line endings :(
html_file.write string
end
end
########################################
--
http://www.pinkjuice.com/