File: sbs.sh
   1 #!/bin/sh
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright (c) 2026 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the "Software"), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 # sbs [options...] [column count...] [files...]
  27 #
  28 # Side-By-Side lays out lines read from all inputs given into several columns,
  29 # separating them with a special symbol. If no named inputs are given, lines
  30 # are read from the standard input, instead of files.
  31 #
  32 # If a column-count isn't given, the script tries to find the most columns
  33 # which can fit a reasonable width-limit; when even a single column can't fit
  34 # that limit, it simply emits all lines, which is the same as using 1 column.
  35 #
  36 # Hint: you can make handy aliases for this tool
  37 #
  38 # alias 0='sbs 0'
  39 # alias 1='sbs 1'
  40 # alias 2='sbs 2'
  41 # alias 3='sbs 3'
  42 # alias 4='sbs 4'
  43 # alias 5='sbs 5'
  44 # alias 6='sbs 6'
  45 # alias 7='sbs 7'
  46 # alias 8='sbs 8'
  47 # alias 9='sbs 9'
  48 #
  49 # The options are, available both in single and double-dash versions
  50 #
  51 #   -h, -help          show this help message
  52 #   -sep               use next argument as the column-separator symbol/string
  53 #   -t, -tab, -tabs    use a single tab as the column-separator
  54 
  55 
  56 sep=''
  57 
  58 while [ $# -gt 0 ]; do
  59     case "$1" in
  60         -h|--h|-help|--help)
  61             awk '/^# +sbs /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  62             exit 0
  63         ;;
  64 
  65         -no-sep|--no-sep|-s|--s|-simple|--simple)
  66             sep=''
  67             shift
  68             continue
  69         ;;
  70 
  71         -sep|--sep)
  72             if [ $# -lt 2 ]; then
  73                 printf "forgot the separator value\n" >&2
  74                 exit 1
  75             fi
  76             shift
  77             sep="$1"
  78             shift
  79             continue
  80         ;;
  81 
  82         -t|--t|-tab|--tab|-tabs|--tabs)
  83             sep="\t"
  84             shift
  85             continue
  86         ;;
  87     esac
  88 
  89     break
  90 done
  91 
  92 num_columns=0
  93 if echo "$1" | grep -q -E '^[+-]?[0-9]+$'; then
  94     num_columns="$1"
  95     shift
  96 fi
  97 
  98 [ "$1" = '--' ] && shift
  99 
 100 # show all non-existing files given
 101 failed=0
 102 for arg in "$@"; do
 103     if [ "${arg}" = "-" ]; then
 104         continue
 105     fi
 106     if [ ! -e "${arg}" ]; then
 107         printf "no file named \"%s\"\n" "${arg}" >&2
 108         failed=1
 109     fi
 110 done
 111 
 112 # in case of errors, avoid showing an empty screen
 113 if [ "${failed}" -gt 0 ]; then
 114     exit 2
 115 fi
 116 
 117 # allow loading lines from multiple files, ensuring no lines are accidentally
 118 # joined across inputs
 119 awk 1 "$@" |
 120 
 121 # ignore leading UTF-8 BOMs (byte-order marks) and trailing carriage-returns:
 122 # the latter in particular will ruin side-by-side output; doing it separately
 123 # using `sed` is faster overall for the script
 124 sed 's-^\xef\xbb\xbf--; s-\r$--' |
 125 
 126 # before laying out lines side-by-side, expand all tabs, using 4 as the
 127 # tabstop width
 128 expand -t 4 |
 129 
 130 # lay lines into side-by-side columns
 131 awk -v sep="${sep}" -v num_columns="${num_columns}" '
 132     BEGIN {
 133         sep = " " sep
 134         sep_width = width(sep)
 135         total_max_width = 79
 136         max_auto_cols = 26
 137 
 138         # num_columns = 0
 139         # detect a leading number, and use it as the max-number of columns
 140         if (ARGV[1] + 0 != 0) {
 141             num_columns = ARGV[1] + 0
 142             delete ARGV[1]
 143         }
 144     }
 145 
 146     # remember all lines; carriage-returns are already removed
 147     { lines[NR] = $0 }
 148 
 149     # width counts items in the string given, ignoring ANSI-style sequences
 150     function width(s) {
 151         gsub(/\x1b\[[0-9;]*[A-Za-z]/, "", s)
 152         return length(s)
 153     }
 154 
 155     # pick a line using a row-column pair as an index
 156     function pick(lines, height, row, col) {
 157         return lines[(col - 1) * height + row]
 158     }
 159 
 160     function ceiling(n) { return (n % 1) ? n - (n % 1) + 1 : n }
 161 
 162     # see if a list of lines can fit the number of columns given exactly
 163     function fits(lines, num_lines, num_cols, height, max_widths, i, j, w, l) {
 164         height = ceiling(num_lines / num_cols)
 165 
 166         # prevent too many empty columns
 167         if (height * num_cols - num_lines >= height) return 0
 168 
 169         for (i = 1; i <= height; i++) {
 170             for (j = 1; j <= num_cols; j++) {
 171                 w = width(pick(lines, height, i, j))
 172                 if (w > total_max_width) return 0
 173                 if (max_widths[j] < w) max_widths[j] = w
 174             }
 175         }
 176 
 177         for (i = 1; i <= height; i++) {
 178             w = 0
 179 
 180             for (j = 1; j <= num_cols; j++) {
 181                 if (j > 1) w += sep_width
 182 
 183                 l = pick(lines, height, i, j)
 184                 if (j > 1 && l != "") w++
 185 
 186                 w += width(l)
 187 
 188                 if (j < num_cols) {
 189                     pad = max_widths[j] - width(l)
 190                     if (pad > 0) {
 191                         if (l == "") pad++
 192                         w += pad
 193                     }
 194                 }
 195 
 196                 if (w > total_max_width) return 0
 197             }
 198         }
 199 
 200         return 1
 201     }
 202 
 203     # auto-detect an appropriate column-count for the list of lines given
 204     function find_max_fit(lines, num_columns) {
 205         if (!fits(lines, NR, 1)) return 1
 206 
 207         for (num_columns = max_auto_cols; num_columns >= 2; num_columns--) {
 208             if (fits(lines, NR, num_columns)) return num_columns
 209         }
 210         return 1
 211     }
 212 
 213     END {
 214         # prevent errors when input has no lines
 215         if (NR < 1) exit
 216 
 217         # auto-fit when given a non-positive count, or when not given a count
 218         if (num_columns < 1) num_columns = find_max_fit(lines)
 219 
 220         # prevent column-count from exceeding the number of input lines
 221         if (num_columns > NR) num_columns = NR
 222 
 223         # emit a single column as lines, quitting right away
 224         if (num_columns < 2) {
 225             for (i = 1; i <= NR; i++) print lines[i]
 226             exit
 227         }
 228 
 229         # prevent a trailing empty column
 230         num_lines = ceiling(NR / num_columns)
 231         if (num_lines * num_columns - NR >= num_lines) num_columns--
 232 
 233         num_lines = ceiling(NR / num_columns)
 234         for (i = 1; i <= num_lines; i++) {
 235             for (j = 1; j <= num_columns; j++) {
 236                 w = width(pick(lines, num_lines, i, j))
 237                 if (max_widths[j] < w) max_widths[j] = w
 238             }
 239         }
 240 
 241         widest = 0
 242         for (i = 1; i <= num_columns; i++) {
 243             if (widest < max_widths[i]) widest = max_widths[i]
 244         }
 245 
 246         # emit lines side by side
 247         for (i = 1; i <= num_lines; i++) {
 248             for (j = 1; j <= num_columns; j++) {
 249                 l = pick(lines, num_lines, i, j)
 250 
 251                 if (j > 1) {
 252                     printf "%s", sep
 253                     if (j != num_columns || l != "") printf " "
 254                 }
 255 
 256                 printf "%s", l
 257 
 258                 if (j < num_columns) {
 259                     pad = max_widths[j] - width(l)
 260                     # if (pad > 0) printf "%*s", pad, ""
 261                     for (k = 1; k <= pad; k++) printf " "
 262                 }
 263             }
 264 
 265             print ""
 266         }
 267     }
 268 '