fork download
  1. require 'tempfile'
  2.  
  3. dir = ARGV.shift
  4. before_word = /\/\/.*/ # 正規表現
  5. after_word = '' # 置換文字列
  6.  
  7. class DirSub
  8. def initialize(dir, before_word, after_word)
  9. @list = []
  10. dirlist(dir).each{|file|
  11. p file
  12. substitute(file, before_word, after_word)
  13. }
  14. end
  15.  
  16. def dirlist(dir)
  17. d = open(dir)
  18.  
  19. d.each{|f|
  20. next if f == '.' || f == '..'
  21.  
  22. fullpath = "#{dir}/#{f}"
  23.  
  24. if directory?(fullpath)
  25. dirlist(fullpath)
  26. else
  27. @list << fullpath if extname(fullpath) == '.c' || extname(fullpath) == '.cpp'
  28. end
  29. }
  30. d.close
  31.  
  32. return @list
  33. end
  34.  
  35. def substitute(file, before_word, after_word)
  36. # 一時ファイルを作成
  37. temp = Tempfile::new(file)
  38.  
  39. open(file, "r"){|f|
  40. f.read.each{|line|
  41. # ファイルの中身を置換
  42. line.gsub!(before_word, after_word)
  43. # 一時ファイルに出力
  44. temp.puts(line)
  45. }
  46. }
  47.  
  48. temp.close
  49. # 一時ファイルを再オープン
  50. temp.open
  51.  
  52. # 一時ファイルの内容で上書きする
  53. open(file, "w"){|f|
  54. p file
  55. temp.each{|line|
  56. puts line
  57. f.puts(line)
  58. }
  59. }
  60. # 作成した一時ファイルを削除
  61. temp.close(true)
  62. end
  63. end
  64.  
  65. DirSub::new(dir, before_word, after_word)
Runtime error #stdin #stdout 0.02s 5528KB
stdin
Standard input is empty
stdout
Standard output is empty