views:

22

answers:

1

Hey,

I am trying to write a ruby script which will look in a directory and its subdirectories for HTML files, open those HTML files and insert the following line just above the closing head tag:

<link rel="stylesheet" href="styles.css" type="text/css" />

I am trying to do this with Ruby because its the only language I am familar with but have access to pretty much any language. Could anyone lend a hand?

Cheers

Eef

+2  A: 
def find_and_replace(dir)
  Dir[dir + '/*.html'].each do |name|
    File.open(name, 'r+') do |f|
      new_file = f.read.sub /^( *)(<\/\s*head>)/, %Q(\\1  <link rel="stylesheet" href="styles.css" type="text/css" />\n\\1\\2)
      f.truncate 0
      f.write new_file
    end
  end
  Dir[dir + '/*/'].each(&method(:find_and_replace))
end

find_and_replace '.'
Adrian
Cheers, excellent little script, learned some stuff I have never seen before, thanks.
Eef
No need for the recursion, you can just use `Dir.glob("**/*.html")` (see http://ruby-doc.org/core/classes/Dir.html#M002322).
Ventero
@Ventero: Thanks for pointing that out. I was wondering if there was a way to do that when I wrote this.
Adrian