#!/usr/bin/awk -f # The MIT License (MIT) # # Copyright © 2024 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # rtsv [options...] [filenames...] # # Realign Tab Separated-Values, by padding with spaces to match each column's # widest value, right-aligning all numbers. function match_number(v) { return match(v, /^[+-]?[0-9]+(\.[0-9]+)?$/) } function match_dot_digits(v) { return match(v, /\.[0-9]+$/) } BEGIN { FS = "\t" } { gsub(/\r$/, "") for (i = 1; i <= NF; i++) { data[NR][i] = $i if (match_number($i)) { if (match_dot_digits($i)) { dd = RLENGTH if (dot_decs[i] < dd) dot_decs[i] = dd iw = RSTART - 1 if (int_widths[i] < iw) int_widths[i] = iw } else { w = length($i) if (int_widths[i] < w) int_widths[i] = w } continue } w = length($i) if (widths[i] < w) widths[i] = w } } END { # fix column-widths using the number-padding info for (i = 1; i <= NF; i++) { w = int_widths[i] + dot_decs[i] if (widths[i] < w) widths[i] = w } for (i = 1; i <= NR; i++) { last = length(data[i]) for (j = 1; j <= last; j++) { if (j > 1) printf " " # put 2-space gaps between columns v = data[i][j] if (!match_number(v)) { # avoid adding trailing spaces at the end of lines printf "%*s", (j == last) ? 0 : -widths[j], v continue } w = length(v) if (match_dot_digits(v)) { dd = RLENGTH iw = RSTART - 1 } else { dd = 0 iw = w } dpad = dot_decs[j] - dd ipad = int_widths[j] - iw if (ipad < 0) ipad = 0 lpad = widths[j] - (ipad + w + dpad) if (lpad < 0) lpad = 0 # avoid adding trailing spaces at the end of lines if (j == last) dpad = 0 printf "%*s%*s%s%*s", lpad, "", ipad, "", v, dpad, "" } printf "\n" } }