using Ruby to rename files and edit their content

Note: If you enjoy this article, you might also check out the Geeky Stuff section.

Recently at work, the web admin for the computer science department came into our lab and told us that my employer's site was broken. The admin had need to make all .php files not act as PHP scripts, and instead, all files with the extension .sphp would now run as PHP scripts. Since my employer's site was built using PHP, that meant all of its pages were showing the source code instead of actually executing. I had to whip up a quick Ruby script in order to:

  1. Rename all .php files to have .sphp as their extension;
  2. Replace all instances of ".php" within those files with ".sphp", to take care of include statements, links, etc.

Here's what I came up with:

Ruby

#!/usr/bin/env ruby
require 'find'
require 'fileutils'

# Used to go through, starting at the directory start_dir and working
# recursively, and rename all files that end in .php to end in .sphp
# because the CS admin got a wild hair.  Also goes through all .php
# and .sphp files and replaces all instances of ".php" in them with
# ".sphp".
def finder( start_dir )
  Find.find( start_dir ) do |path|
    if FileTest.file?( path )
      if path =~ /\.php$/i
        old_name = File.basename( path )
        new_name = old_name.gsub( /\.php$/, '.sphp' )
        dir = path.gsub( /#{old_name}$/, '' )
       
        if File.exists?( dir + old_name )
          puts "#{dir + old_name} to #{dir + new_name}\n"
         
          # Since the code is part of a Subversion repository, we use
          # the 'svn' command to let Subversion rename the file
          system( "svn mv #{dir + old_name} #{dir + new_name}" )
        end
      elsif path =~ /\.sphp$/i || path =~ /\.php$/i
        puts "Replacing instances of '.php' in #{path}\n"
        system( %Q{ruby -pe 'gsub(/\\.php/, ".sphp")' -i #{path} } )
      end
    end
  end
end

finder( '.' )

6 Comments / Add your own »

Add a Comment

required
will not be published; required

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comments RSS feed / TrackBack URI