Ruby search and replace across files
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="styl开发者_运维问答esheet" 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
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 '.'
精彩评论