#!/usr/bin/env ruby # user settings source_file = '/Users/Dan/Desktop/Student Email/emails.csv' output_base_directory = '/Users/Dan/Desktop/Student Email/' output_file = 'Email Username & Password.txt' # set the following variable to 'true' if you want the script to remove any # non alphanumeric characters from theuser's name before creating the output # directory for that user clean_up_name = false # the block of text we will later save to # a file, replacing some items, eg %Password% # with actual values text = ' Your new Student email address is %EmailAddress% and your password is %Password% you will be required to change you password the first time you login. Student email is now located at http://studentemail.domain.com ' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # ensure the output directory has a trailing '/' on it output_base_directory = "#{output_directory}/" unless output_base_directory[-1,1] == '/' # ensure the output directory exists unless File.exists?(output_base_directory) && File.directory?(output_base_directory) puts "Output directory: '#{output_base_directory}' does not appear to exist" exit end # ensure the source file exists unless File.exists?(source_file) puts "Source file: '#{source_file}' does not appear to exist" exit end # open the source file File.open(source_file) do |f| # process each line f.each_with_index do |line, index| # split the line by commas email, password, name = line.split(',') # trim any whitespace or carriage # returns from the variables email.strip! password.strip! name.strip! # set the name for the file we will create. For safety # we will replace any odd characters in the user name # with underscores. We will also need to create the # directory for it. output = clean_up_name ? output_base_directory + name.gsub(/[^a-zA-Z0-9]/, '_') + '/' : output_base_directory + name + '/' Dir.mkdir(output) unless File.exists?(output) output = output + output_file # take a copy of our text and replace the placeholders # in the block of text with the real name, email, etc mytext = String.new(text) mytext.gsub!('%EmailAddress%', email) mytext.gsub!('%Password%', password) mytext.gsub!('%Name%', name) # write the new file File.open(output, 'w') { |o| o.write(mytext) } # just some output to the console so we can see what # is happening if File.exists? output puts "Processed line: #{index} (#{name}) and saved file as: #{output}" else puts "Failed to process line: #{index} (#{name})." end end end puts "All done"