Last active
September 11, 2018 07:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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