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:
- Rename all .php files to have .sphp as their extension;
- Replace all instances of ".php" within those files with ".sphp", to take care of
includestatements, links, etc.
Here's what I came up with:
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( '.' )
That looks so fun. I’d love to learn Ruby except… My server doesn’t support it. :(
This line was very useful for me, thanks! I was wondering how to rename files and deal with svn in a migration, it never occurred to me to simply speak to svn from inside the migration. It’s a nice easy way to rename as well :)
system( “svn mv #{dir + old_name} #{dir + new_name}” )
Pingback: Edit Filenames and Content with Ruby. | Menekali
This looks helpful, but I don’t understand something. When does the line
elsif path =~ /\.sphp$/i || path =~ /\.php$/iget called? I don’t understand an elsif that checks the same condition as the if. Am I missing something?
Er, Luke, good point. I don’t know why I did the
elsifwith one of the same conditions as theif.Pingback: ProDevTips - dev related notes and tutorials » Blog Archive » Ruby File Renamer
Pingback: Answer by Sarah Vessels for Prefered terminal scripting language — Three till Seven