Skip to content

Instantly share code, notes, and snippets.

@nicholasf
Created July 7, 2009 04:49
Show Gist options
  • Save nicholasf/141889 to your computer and use it in GitHub Desktop.
Save nicholasf/141889 to your computer and use it in GitHub Desktop.
A simple script to remove specified text from all files in a directory tree
#!/usr/bin/env ruby
#
# A simple script to remove specified text from all files in a directory tree
# remove_offending.rb <target_dir>
# bad string - <iframe src="http://odmarco.com/arwe/?736361acd09ca9717c9462514beb5205" width=0 height=0 style="hidden" frameborder=0 marginheight=0 marginwidth=0 scrolling=no></iframe>
require 'fileutils'
include FileUtils::Verbose
@offending_line = /<iframe.+http:\/\/odmarco.com.+\/iframe>/
@@count = 0
root_dir = ARGV[0]
def clean(file_name)
return if File.directory?(file_name)
replica = file_name + ".cleaning"
FileUtils.mv(file_name, replica)
puts "cleaning #{file_name}..."
File.open(file_name, "w") do |out|
IO.foreach(replica) do |line|
if line =~ @offending_line
puts "FOUND - #{line}"
line.gsub!(@offending_line, "")
puts "CLEAN - #{line}"
@@count = @@count + 1
end
out << line
end
end
FileUtils.rm(replica, :force => true)
end
def traverse(dir)
puts "Looking in #{dir}"
entries = Dir.entries(dir)
puts "#{entries.size} files or directories ..."
for entry in entries
rel_path = File.join(dir, entry)
if entry == "." or entry == ".."
next
elsif File.directory?(rel_path)
traverse(rel_path)
else
begin
clean(rel_path)
rescue StandardError => boom
puts "couldn't open #{entry}, #{boom.to_s}"
end
end
end
end
traverse(root_dir)
FileUtils.rm_rf("*.cleaning")
puts "Finished. Cleaned #{@@count} occurrences."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment