Last active
April 7, 2019 13:01
-
-
Save kou1okada/87ab351034a2427cf4d51603189e9a21 to your computer and use it in GitHub Desktop.
align_columns.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/sh | |
| exec ruby -x "$0" "$@" | |
| #!ruby | |
| # coding: utf-8 | |
| # | |
| # align_column.rb | |
| # Copyright (c) 2019 Koichi OKADA. All rights reserved. | |
| # This script is destributed under the MIT license. | |
| # | |
| require 'optparse' | |
| require 'tempfile' | |
| require 'unicode/display_width' # Requires: gem install unicode-display_width | |
| opts = OptionParser.new | |
| opts.banner = "Usage: #{File.basename $0} [<options>] [<files> ...]\n" | |
| opts.banner += "Options:" | |
| opts.on("-Fpattern", "Pattern for field separator"){|v| $; = Regexp.new v} | |
| opts.parse! ARGV | |
| def Array.zip(a,b); a.length > b.length ? a.zip(b) : b.zip(a); end | |
| class String | |
| def drop_sgr; self.gsub(/\e\[[0-9;]*m/, ""); end | |
| end | |
| # Determine columns widths | |
| w = [0] | |
| tmp = Tempfile.new(File.basename $0) | |
| while gets | |
| tmp.print $_ | |
| $_.chomp! | |
| $F = $_.split | |
| w1 = $F.map{|s| Unicode::DisplayWidth.of s.drop_sgr} | |
| w = Array::zip(w, w1).map{|a| a.compact.max} | |
| end | |
| tmp.close | |
| # Align columns | |
| tmp.open | |
| while $_ = tmp.gets | |
| $_.chomp! | |
| $F = $_.split | |
| puts $F.zip(w).map{|f,w| | |
| pad = " " * [(w||0) - Unicode::DisplayWidth.of(f.drop_sgr), 0].max | |
| /^[-+]?[0-9]*([.][0-9]+)?$/ =~ f ? pad + f : f + pad | |
| }.join(" ") | |
| end | |
| tmp.close! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment