-
Notifications
You must be signed in to change notification settings - Fork 0
/
show_rows_with_column_ct.rb
67 lines (54 loc) · 1.66 KB
/
show_rows_with_column_ct.rb
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
64
65
66
#!/usr/bin/env ruby
# Takes path to table, number of columns, delimiter name, and optional row limit
# Prints to screen rows with that number of columns
require 'csv'
require 'fileutils'
require 'optparse'
require 'pp'
require 'pry'
options = {}
OptionParser.new do |opts|
opts.banner = 'Usage: show_rows_with_column_ct.rb -i path-to-input-file -d {delimiterName} -c INTEGER -l INTEGER'
opts.on('-i', '--input PATH', 'Path to input table file') do |i|
options[:input] = File.expand_path(i)
end
opts.on('-d', '--delimiter STRING', 'Delimiter name. Must be: tab, pipe, or comma') do |d|
case d
when 'tab'
options[:delimiter] = '\t'
when 'pipe'
options[:delimiter] = '|'
when 'comma'
options[:delimiter] = ','
else
puts '-d (--delimiter) must be tab, pipe, or comma. Type the string, not the character.'
exit
end
end
opts.on('-c', '--columns INT', Integer, 'Number of columns in rows that will be printed') do |c|
options[:columns] = c
end
opts.on('-l', '--limit [INT]', Integer, 'Number of rows that will be printed') do |l|
options[:limit] = l || nil
end
opts.on('-h', '--help', 'Prints this help') do
puts opts
exit
end
end.parse!
structure = {}
File.readlines(options[:input]).each do |row|
len = row.chomp.split(options[:delimiter]).length
if structure.key?(len)
structure[len] << row.chomp
else
structure[len] = [row.chomp]
end
end
rows = structure[options[:columns]]
if rows.nil? || rows.empty?
puts "No rows with #{options[:columns]} columns"
else
to_print = options[:limit].nil? ? rows.length - 1 : options[:limit] - 1
rows[0..to_print].each{ |r| puts r }
end