Pages

Sponsorship

40% off your First Order with GoDaddy.com!

Jan 29, 2010

Substitute Strings in Files with Ruby


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
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
}
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment