Skip to content

Instantly share code, notes, and snippets.

@sms420
Created December 18, 2009 07:57
Show Gist options
  • Select an option

  • Save sms420/259352 to your computer and use it in GitHub Desktop.

Select an option

Save sms420/259352 to your computer and use it in GitHub Desktop.
find replace
#!/usr/local/bin/ruby1.9 -w
# findReplace.rb
#####################################
# #
# searches files in specified #
# path for specific string #
# and then replaces that string #
# #
#####################################
glob_path, exp_search,
exp_replace = '/home/sean/ruby-dev/findReplace/*.txt',
'homey', #string you are looking for
'dude' #what you will replace that string with
Dir.glob(glob_path).each do |file|
buffer = File.new(file,'r').read.gsub(/#{exp_search}/,exp_replace)
File.open(file,'w') {|fw| fw.write(buffer)}
end
=begin
SAMPLE OUTPUT:
sean@dude:~/ruby-dev/findReplace$ cat file02.txt ; cat file01.txt
file 2
homey
yo
file 1
homey
yo
sean@dude:~/ruby-dev/findReplace$ ./findReplace.rb
sean@dude:~/ruby-dev/findReplace$ cat file02.txt ; cat file01.txt
file 2
dude
yo
file 1
dude
yo
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment