-
Notifications
You must be signed in to change notification settings - Fork 0
/
divider
executable file
·63 lines (50 loc) · 1.59 KB
/
divider
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env ruby
# Usage
# Run divider "filename" "number of files to be divided"
# Command should look like ./divider --file="/Users/mergul/Downloads/person.csv" --count=4
require "csv"
require "pry"
def process_arguments
options = {}
ARGV.each do |arg|
if arg.start_with?("--")
key_value_pair = arg.split("=")
key = key_value_pair[0][2..-1].to_sym
value = key_value_pair[1]
options[key] = value
end
end
file_name = options[:file]
number_of_files = options[:count]
if file_name.nil? || number_of_files.nil?
puts "Please provide both arguments."
elsif options.count > 2
puts "Only two arguments are accepted file name and number of files to be divided"
else
puts "The provided arguments are file: #{file_name.split("/").last} and number_of_files: #{number_of_files}"
run_divide(options)
end
end
def read_csv_file(file)
CSV.read(file, headers: true, col_sep: ",", quote_char: '"', liberal_parsing: false)
rescue => e
puts "Something wrong with reading the file: #{e.message}"
end
def file_headers(read_csv_file)
read_csv_file.headers
end
def run_divide(options)
division = CSV.read(options[:file], headers: true).count / options[:count].to_i
options[:count].to_i.times do |index|
start = index * division
finish = start + division - 1
puts "#{start}-#{finish}.csv is generated.."
CSV.open("#{start}-#{finish}_rows.csv", "w+") do |row|
row << file_headers(read_csv_file(options[:file]))
read_csv_file(options[:file])[start..finish].each do |d|
row << d
end
end
end
end
process_arguments