2010-07-17 79 views
0

我試圖寫一個Ruby腳本,它看起來在一個目錄及其對HTML文件的子目錄,打開這些HTML文件,然後插入以下行結束標記上面:紅寶石搜索和替換整個文件

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

我想用Ruby做到這一點,因爲它是我唯一的語言,但可以訪問幾乎任何語言。任何人都可以伸出援手嗎?

乾杯

EEF

回答

4
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 '.' 
+0

歡呼聲中,出色的小腳本,學到了一些東西,我從來沒有見過的,謝謝。 – RailsSon 2010-07-17 21:57:18

+1

無需遞歸,您可以使用'Dir.glob(「**/*。html」)(請參閱http://ruby-doc.org/core/classes/Dir.html#M002322)。 – Ventero 2010-07-17 22:00:28

+0

@Ventero:謝謝你指出。我想知道是否有辦法做到這一點,當我寫這個。 – Adrian 2010-07-17 22:02:10