Top

substitute strings in files


Ruby / Rails Code

Please Register to submit score.
Bookmark and Share
Average Score  7.0 (of 1 scores)
Date Added  Aug 24, 2005
Last Updated  Aug 25, 2005

Description

Uses a list of regular expressions and replacement strings
to make changes in text files.

Put in file "edit-all.rb" and run with
ruby edit-all.rb *.txt

Now accepts the target and the replacement from the command line or from the keyboard.

Grab the Code

##
##  Make substitutions in a slew of files.
##  Backups having the extension ".bak" are made.
##  To make it descend into all subdirectories:
##    ruby edit-all.rb **/*.txt
##
##  You may include the target & replacement on the
##  command line by using the -x switch:
##    ruby edit-all.rb -x 'original' 'replacement' *.txt
 
 
# Only files below the current level?
only_deep = false
 
pairs = [
#   /Original text\./,  "Edited in place.",
#   /(\w+) text\./,  '\1 nonsense.'
]
 
if '-x' == ARGV.first
  ARGV.shift
  pairs = [ Regexp.new( ARGV.shift ), ARGV.shift ]
end
 
if pairs.size == 0
  puts "\nIn the replacement text, use \\1 for the first"
  puts "capture, \\2 for the second, etc.\n\n"
  loop {
    print "regular expression: "
    s = STDIN.gets.chomp
    break if s == ""
    pairs << Regexp.new( s )
    print "replacement: "
    pairs << STDIN.gets.chomp
  }
end
 
raise "\npairs must contain even number of items."  if
  1 == pairs.size % 2
 
ARGV.reject! { |f| File.directory?(f) }
ARGV.reject! { |f| f !~ /\// }   if only_deep
 
if ARGV.empty?
  puts "I have no filenames."
  exit
end
 
# Turn on in-place editing.  If you're certain that
# nothing can go wrong, you may want to turn off
# creation of backups by changing ".bak" to "" (won't
# work under windoze).
$-i = ".bak"
 
ARGF.each{ |line|
  (0 ... pairs.size).step(2) { |i|
      line.gsub!( pairs[i], pairs[i+1]  )
  }
  puts line
}
 

Comments

  (3)  RSS
Hawkee
Comments: 1,122
 
Ruby / Rails Snippet:  substitute strings in files
Posted Aug 24, 2005
Maybe rather than editing the code with the string and replacement string, it can accept them from the command line?
Hawkee
Comments: 1,122
 
Ruby / Rails Snippet:  substitute strings in files
Posted Aug 31, 2005
Nice, I see you've added command line support. This can be very useful.
RichardOnRails
Comments: 1
 
Ruby / Rails Snippet:  substitute strings in files
Posted May 13, 2010
Nicely written. When I wrote file-searching type snippets, I usually create convoluted code. And I think your code will be useful to me right now. Thanks for posting it.

Regards,
Richard

Commenting Options

Register or Login to Hawkee.com or use your Facebook or Twitter account by clicking the corresponding button below.

  

Bottom