/
align-table
executable file
路99 lines (80 loc) 路 2.58 KB
/
align-table
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env ruby
#
# Vertically aligns multiple columns, which are
# delimited by a user-defined regular expression,
# that are present in the input given on STDIN.
#
# For example, the following input:
#
# short text = foo = hello
# really long text = bar = world
# wide operator <=> moz <=> again
#
# yields the following output:
#
# short text = foo
# really long text = bar
# wide operator <=> moz
#
#--
# Written in 2007 by Suraj N. Kurapati
def align_table lines, delimiter, selector, rejector, justifier
delim_regexp = /#{delimiter}/
# determine columns widths
widths = Hash.new(0)
rows = lines.map do |line|
line.chomp!
if line =~ selector and line !~ rejector and line =~ delim_regexp
fields = line.split(delim_regexp)
fields.each {|f| f.strip! }
fields.unshift line[/\A[ \t]*/] # whitespace margin
delims = line.scan(delim_regexp)
delims[0..-2].each {|d| d << ' ' }
delims[1..-1].each {|d| d.insert(0, ' ') }
#delims.each {|d| d.insert(0, ' ') << ' ' }
delims.unshift nil
cols = fields.zip(delims).flatten.compact
cols.each_with_index do |c, i|
widths[i] = [c.length, widths[i]].max
end
else
line
end
end
# equalize column widths
rows.map! do |row|
if row.is_a? Array
cols = []
row.each_with_index do |col, i|
cols[i] = col.send(justifier, widths[i])
end
cols.join.rstrip
else
row
end
end
rows.join("\n")
end
if $0 == __FILE__
require 'optparse'
parser = OptionParser.new
parser.on '-h', '--help', 'show this help message' do
puts File.read(__FILE__).split(/^$/).first, nil, parser
exit
end
parser.on '-d', '--delimiter REGEXP', 'input column delimiter',
"(default: #{(delimiter = /[[:punct:]]*=[[:punct:]]*/).inspect})\n",
String do |arg| delimiter = arg end
parser.on '-j', '--justify METHOD', 'justify text inside columns',
'(choices: ljust, rjust, or center)',
"(default: #{justifier = 'center'})",
String do |arg| justifier = arg end
parser.on '-m', '--select REGEXP', 'only wrap lines that match REGEXP',
"(default: #{(selector = //).inspect})",
Regexp do |arg| selector = arg end
parser.on '-M', '--reject REGEXP', 'do not wrap lines that match REGEXP',
"(default: #{(rejector = nil).inspect})",
Regexp do |arg| rejector = arg end
parser.parse ARGV
puts align_table(STDIN.readlines, delimiter, selector, rejector, justifier)
end