Ruby実用例 〜複数テキストファイル中文字列の置換〜 の変更点


 テキストファイル中の文字列を置換するには、エディタやワープロソフトの機能を使えば簡単にできます。しかし、置換したいファイルが大量にある場合は、一つずつファイルを開いて処理するのは大変です。そのような場合は、ディレクトリ中の全てのテキストファイルを再帰的に処理するスクリプトをつくって対処すると楽することができます。
 
 * サンプルコード [#m67515df]
 
  #!/usr/bin/env ruby
  # 引数で与えられたディレクトリを再帰的に処理し "*.txt" ファイル中の文字列を置換
  
  require 'tempfile'
  
  dir = ARGV.shift
  before_word = /^.. important\s*?::.*?\n/  # 正規表現
  after_word = '.. admonition:: theorem'  # 通常文字列
  
  class DirSub
    def initialize(dir, before_word, after_word)
      @list = []
      dirlist(dir).each{|file|
        p file
        #substitute(file, before_word, after_word)
      }
    end
  
    def dirlist(dir)
      d = Dir::open(dir)
      d.each{|f|
        next if f == '.' || f == '..'
        
        fullpath = "#{dir}/#{f}"
        
        if File::directory?(fullpath)
          dirlist(fullpath)
        else
          @list << fullpath if File::extname(fullpath) == '.txt'
        end
      }
      d.close
      
      return @list
    end
  
    def substitute(file, before_word, after_word)
      temp = Tempfile::new('dirsub', '/tmp')
      
      File::open(file, 'r'){|f|
        f.read.each{|line|
          line.gsub!(before_word, after_word)
          temp.puts(line)
        }
      }
      
      temp.close
      temp.open
      
      File::open(file, 'w'){|f|
        p file
        temp.each{|line|
          puts line
          f.puts(line)
        }
      }
      
      temp.close(true)
    end
  end
  
  DirSub::new(dir, before_word, after_word)
Valid XHTML 1.1! home > コンピュータ > プログラミング >
リロード   新規 編集 差分 添付 複製 改名   トップ 一覧 検索 最終更新 バックアップ   ヘルプ   最終更新のRSS
Modified by 物理のかぎプロジェクト PukiWiki 1.4.5_1 Copyright © 2001-2005 PukiWiki Developers Team. License is GPL.
Based on "PukiWiki" 1.3 by yu-jiPowered by PHP 5.3.29HTML convert time to 0.002 sec.