0
我试图写一个Ruby脚本,它看起来在一个目录及其对HTML文件的子目录,打开这些HTML文件,然后插入以下行结束标记上面:红宝石搜索和替换整个文件
<link rel="stylesheet" href="styles.css" type="text/css" />
我想用Ruby做到这一点,因为它是我唯一的语言,但可以访问几乎任何语言。任何人都可以伸出援手吗?
干杯
EEF
我试图写一个Ruby脚本,它看起来在一个目录及其对HTML文件的子目录,打开这些HTML文件,然后插入以下行结束标记上面:红宝石搜索和替换整个文件
<link rel="stylesheet" href="styles.css" type="text/css" />
我想用Ruby做到这一点,因为它是我唯一的语言,但可以访问几乎任何语言。任何人都可以伸出援手吗?
干杯
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 '.'
欢呼声中,出色的小脚本,学到了一些东西,我从来没有见过的,谢谢。 – RailsSon 2010-07-17 21:57:18
无需递归,您可以使用'Dir.glob(“**/*。html”)(请参阅http://ruby-doc.org/core/classes/Dir.html#M002322)。 – Ventero 2010-07-17 22:00:28
@Ventero:谢谢你指出。我想知道是否有办法做到这一点,当我写这个。 – Adrian 2010-07-17 22:02:10