File: backsort.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 # backsort [options...] [names/indices...]
  27 #
  28 # BACKward-SORT (numerically) using values from the columns whose names match
  29 # the arguments given, either exactly, case-insensitively, as 1-based indices,
  30 # or even as negative/backward indices.
  31 #
  32 # Sorting happens by comparing fields in the order given, stopping comparisons
  33 # as soon as (ordering) ties are broken.
  34 #
  35 # Input always comes from the standard input. The output is always lines of
  36 # TSV (tab-separated values), even when the input lines from stdin aren't.
  37 #
  38 # The options are, available both in single and double-dash versions
  39 #
  40 #   -h, -help     show this help message
  41 #   -no-header    first input line isn't a header/column-names line
  42 #   -t, -tsv      force TSV-input mode, no matter the first line
  43 
  44 
  45 tsv=0
  46 header=1
  47 
  48 case "$1" in
  49     -h|--h|-help|--help)
  50         awk '/^# +backsort /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  51         exit 0
  52     ;;
  53 
  54     -no-header|--no-header)
  55         header=0
  56         shift
  57     ;;
  58 
  59     -t|--t|-tsv|--tsv) tsv=1; shift ;;
  60 
  61     --) shift ;;
  62 esac
  63 
  64 awk -v tsv="${tsv}" -v header="${header}" '
  65     function findcol(name, lowname, i) {
  66         for (i = 1; i <= NF; i++) {
  67             if (name == $i) return i
  68         }
  69 
  70         for (i = 1; i <= NF; i++) {
  71             if (lowname == tolower($i)) return i
  72         }
  73 
  74         if (1 <= name && name <= NF) return name + 0
  75         if (name < 0 && -name <= NF) return NF + name + 1
  76 
  77         return 0
  78     }
  79 
  80     BEGIN {
  81         if (tsv) FS = "\t"
  82 
  83         for (i = 1; i < ARGC; i++) {
  84             colnames[i] = ARGV[i]
  85             lownames[i] = tolower(colnames[i])
  86             delete ARGV[i]
  87         }
  88     }
  89 
  90     { gsub(/\r$/, "") }
  91 
  92     NR == 1 {
  93         if (!tsv && ($0 ~ /\t/)) {
  94             FS = "\t"
  95             $0 = $0
  96         }
  97 
  98         width = NF
  99         given = ARGC - 1
 100 
 101         for (i = 1; i <= given; i++) {
 102             j = findcol(colnames[i], lownames[i])
 103             if (j > 0) pos[++numcols] = j
 104 
 105             if (j == 0) {
 106                 fmt = "no column match for \"%s\"\n"
 107                 printf(fmt, colnames[i]) > "/dev/stderr"
 108                 errors++
 109             }
 110         }
 111 
 112         if (errors > 0) exit 1
 113 
 114         cmd = "sort -s -t \"\t\""
 115         for (i = 1; i <= numcols; i++) {
 116             cmd = cmd sprintf(" -k%d,%drn", pos[i], pos[i])
 117         }
 118 
 119         if (header) {
 120             for (i = 1; i <= width; i++) {
 121                 if (i > 1) printf "\t"
 122                 printf("%s", $i)
 123             }
 124             print ""; fflush()
 125 
 126             next
 127         }
 128     }
 129 
 130     {
 131         for (i = 1; i <= width && i <= NF; i++) {
 132             if (i > 1) printf "\t" | cmd
 133             printf("%s", $i) | cmd
 134         }
 135         # fill-in missing trailing TSV fields
 136         for (i = NF + 1; i <= width; i++) printf "\t" | cmd
 137         # treat extra columns as part of the last one
 138         for (j = width + 1; j <= NF; j++) printf(" %s", $i) | cmd
 139         print "" | cmd
 140     }
 141 ' "$@"