In: Computer Science
write a script in ruby to automate user account creation in Linux using a CSV file. Username is a combination of first initial last initial of the first name and last name in the last name followed by the first initial last initial(Ex. Sam Smith = smithsm). If two or more employees had the same first and last name appends a number to the end of the username. After accounts are created write the first and last names along with their username to a CSV file
CSV Example:
first_name last_name
Bob Key
Jeff Scolding
Peter Van't Blob
Sam Smith
Sam Smith
Program
require 'csv'
arr=CSV.read("input.csv")
outputArr=[['first_name'],['last_name'],['username']]
arr.each_with_index do |item, index|
if index != 0 then # skip first row as it is heading of column
# puts arr[index][0]
outputArr[0].push( arr[index][0]) # firstname
outputArr[1].push( arr[index][1]) # lastname
initial_char=arr[index][0][0] # get last name from arr
last_char=arr[index][0][arr[index][0].length-1] # get first name last char
username=arr[index][1]+initial_char+last_char # join last name and first name initial char and firstname last char
if outputArr[2].include? username then # if username already exists
username=username+index.to_s # append index number converted to string to username
end
username=username.downcase # cnvert username to lowercase
outputArr[2].push( username)
end
end
csvArr=[]
for i in 0..outputArr[0].length()-1 # loop to convert rows to columns
tempArr=[]
for j in 0..outputArr.length()-1
tempArr.push(outputArr[j][i])
end
csvArr.push(tempArr)
end
File.write("output.csv", csvArr.map(&:to_csv).join)
puts "csvArr array writen to output.csv successfully"
OUtput
> ruby parseCsv.rb
csvArr array writen to output.csv successfully
input.csv
output.csv
Both csv files will be in same folder where .rb file is kept