## -*- Ruby -*- ## filesed -s -r [ ] ## Replace pattern by string in all given files. ## Testversion: parses commandline but doesn't change files def using print <<-'ENDE' Usage: filesed -s -r [ ] ENDE exit 1 end def filesed!(pattern, replaceString, filename) regexPattern = Regexp.compile(pattern) count = 0 tmpFilename = "#{filename}.#{Time.now.usec}" tmpFile = File.new(tmpFilename, "w") srcFile = File.open(filename) srcFile.each_line do |line| tmpFile.print line.gsub(regexPattern) { |match| count += 1 replaceString } end tmpFile.close srcFile .close #~ File.rename(tmpFilename, filename) return count end pattern = nil replacer = nil optionsArt = nil files = Array.new $*.each do | argument | if (/^-.*/ =~ argument) != nil # option if (/^-[rs]/ =~ argument) == nil then using end optionsArt = argument[1] # expect option parameter else case optionsArt when 's'[0] then pattern = argument when 'r'[0] then replacer = argument else files.push(argument) end optionsArt = nil end end using unless pattern && replacer && !files.empty? counter = 0 files.each { |filename| counter += filesed!(pattern, replacer, filename) } print "Replaced: #{counter.to_s}\n"