Reputation: 20637
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
Upvotes: 0
Views: 1337
Reputation: 15171
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 '.'
Upvotes: 4