Skip to content

Instantly share code, notes, and snippets.

@Ellyll
Last active Sep 11, 2018
Embed
What would you like to do?
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