substitute strings in files

By hawker on Aug 24, 2005

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.

##  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
  pairs = [ ARGV.shift ), ARGV.shift ]

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 << s )
    print "replacement: "
    pairs << STDIN.gets.chomp

raise "\npairs must contain even number of items."  if
  1 == pairs.size % 2

ARGV.reject! { |f| }
ARGV.reject! { |f| f !~ /\// }   if only_deep

if ARGV.empty?
  puts "I have no filenames."

# 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


Sign in to comment.
RichardOnRails   -  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.


Hawkee   -  Aug 31, 2005

Nice, I see you\'ve added command line support. This can be very useful.

Hawkee   -  Aug 24, 2005

Maybe rather than editing the code with the string and replacement string, it can accept them from the command line?

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.