網頁

2009年11月19日 星期四

使用Ruby修改檔案內容

以下是使用Ruby修改檔案,主要目的是修改sympa(mailing list)中許多目錄(list)中的config檔案內容。
using ruby modify file content.
config的內容中找到"owner_include"區段將"profile normal"替換成"profile privileged"。
  1. <--
  2. Dir.chdir("/usr/local/sympa/expl")
  3. Dir.glob("*-*").each do |x|
  4.   if File::directory?(x)
  5.     config_file = File.join(x, 'config')
  6.     if File.exist?(config_file)
  7.       puts config_file
  8.       flag = false
  9.       File.open(config_file, 'r+') do |f|
  10.         out = ""
  11.         f.each do |line|
  12.           if line =~ /owner_include/
  13.             flag = true
  14.           elsif line =~ /^$/
  15.             flag = false
  16.           elsif flag == true
  17.             if line =~ /profile normal/
  18.               line = "profile privileged\n"
  19.             end
  20.           end
  21.           out << line
  22.         end
  23.         #write to file
  24.         f.pos = 0 #from line 1
  25.         f.print out #write
  26.         f.truncate(f.pos) #truncate after current position
  27.       end
  28.     end
  29.   end
  30. end

沒有留言: