Skip to content

Instantly share code, notes, and snippets.

@mikker
Created October 29, 2012 12:09
Show Gist options
  • Select an option

  • Save mikker/3973207 to your computer and use it in GitHub Desktop.

Select an option

Save mikker/3973207 to your computer and use it in GitHub Desktop.
Merge text files into one
#!/usr/bin/env ruby
# coding: utf-8
Encoding.default_external = "utf-8"
#############################################
# A ruby script for merging of text files #
# By Mikkel Malmberg (brnbw.com) #
#############################################
require 'optparse'
require 'fileutils'
# Defaults
options = {
glob: '(.*).txt',
output: 'output.txt',
dir: Dir.pwd,
destructive: false,
append: false }
# Options
OptionParser.new do |opts|
opts.banner = "Usage: merge_files [options]"
opts.on("-g", "--glob [FILES]", "default: '(.*).txt'") { |glob| options[:glob] = glob }
opts.on("-o", "--output [DESTINATION]", "default: 'output.txt'") { |filename| options[:output] = filename }
opts.on("-d", "--dir [DIRECTORY]", "default: Current directory") { |dir| options[:dir] = dir }
opts.on("-D", "--destructive", "default: false") { |destructive| options[:destructive] = true }
opts.on("-a", "--append", "default: false") { |append| options[:append] = true }
opts.on_tail("-h", "--help", "Show this message") { puts opts; exit }
end.parse!
# DO THE WORK
# Find 'em
Dir.chdir(File.expand_path(options[:dir])) # Change to the given dir
files = Dir["*"].grep(%r{#{options[:glob]}}) # Find the files
puts "Matched files: \n#{files.join(", ")}"
# Make string of new content
content = (options[:append] ? files : files.reverse).map do |file|
"#{file}:\n#{open(file).read}\n\n"
end.join
# Pre- or append the new content
current = File.open(options[:output], "a+").read
current = "" if options[:destructive] # Empty the file if we're destructive
File.open(options[:output], "w+") do |file|
file << (options[:append] ? content + current : current + content)
end
# DELETE THE EVIDENCE (if told to)
if options[:destructive]
files.delete(options[:output]) # Don't remove the output file, if we're merging into it
files.each { |file| FileUtils.rm(file) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment