I'm more of a windows guy and am very novice when it comes to unix. I was trying to figure out how to do a find/replace searching in a specified path. I ended up writing it in Ruby. This is what I came up with.


require 'find' 
if ARGV.size <= 3 || ARGV[0] == '-h'
  puts "findreplace.rb Finds and replaces strings in the given directory."
  puts "syntax: findreplace.rb PATH find_string replace_string [ignore_dirs]"
  exit
end

Find.find(ARGV[0]) do |file_name| 
  if File.file? file_name
    file = File.new(file_name)
    lines = file.readlines
    file.close

    changes = false
    lines.each do |line|
      changes = true if line.gsub!(/#{ARGV[1]}/, ARGV[2])
    end

    # Don't write the file if there are no changes
    if changes
      file = File.new(file_name,'w')
      lines.each do |line|
        file.write(line)
      end
      file.close
    end
  end

  Find.prune if ARGV[3] && file_name =~ /#{ARGV[3]}/  
end

1 Response to “Ruby find and replace in files script”

  1. Peter Says:

    I think there is a typo in line 2 instead of 'ARGV.size <= 3' should be 'ARGV.size < 3'

Leave a Reply