Skip to content

Instantly share code, notes, and snippets.

@Ellyll
Last active September 11, 2018 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ellyll/f8514f94f3d7e4075f9ba2dc5e31de56 to your computer and use it in GitHub Desktop.
Save Ellyll/f8514f94f3d7e4075f9ba2dc5e31de56 to your computer and use it in GitHub Desktop.
Replace words in text files in a directory with replacements in csv file
require 'fileutils'
inputDirectory = "/home/ellyll/Dropbox/Arbrofion/TextReplacer"
outputDirectory = "/tmp/ReplacedFiles"
replacementsFile = "/home/ellyll/Dropbox/Arbrofion/TextReplacer/replacements.csv"
# Read replacements csv file
replacements = File.readlines(replacementsFile).collect {|line| line.chomp.split(",") }
replacements.each {|r| puts "replace \"#{r[0]}\" with \"#{r[1]}\"" }
# Get a list of all the files and directories in the inputDirectory (recursively) and keep only the files
files = Dir.glob("#{inputDirectory}/**/*").keep_if {|f| File.file?(f) }
files.each do |f|
# Get the full name of the output file to be written in the output directory
newfilename = outputDirectory + f[inputDirectory.length, f.length-inputDirectory.length]
# Get the directory path and create directories as needed
newfiledir = File.dirname(newfilename)
unless Dir.exist?(newfiledir)
FileUtils.mkdir_p(newfiledir)
end
print "Doing: #{f} to #{newfilename}\n"
outfile = File.open(newfilename, 'w')
File.foreach(f) do |line|
str = line
replacements.each do |r|
str.gsub!(r[0], r[1])
end
outfile.puts str
end
outfile.close()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment