#!/bin/sh # The MIT License (MIT) # # Copyright (c) 2026 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. # regsort [option...] [regex...] [files...] # # Regular Expression Group SORT groups/sorts lines according to common results # of matching the extended-mode regular-expression given. Each match group # starts appearing in the output depending on the order the first line matching # it appeared in the input. # # The options are, available both in single and double-dash versions # # -i, -ins, -insensitive match the regex given case-insensitively # -h, -help show this help message case "$1" in -h|--h|-help|--help) awk '/^# +regsort /, /^$/ { gsub(/^# ?/, ""); print }' "$0" exit 0 ;; esac case_insensitive=0 case "$1" in -i|--i|-ins|--ins|-insensitive|--insensitive) case_insensitive=1 shift ;; esac [ "$1" = '--' ] && shift if [ $# -eq 0 ]; then awk '/^# +regsort /, /^$/ { gsub(/^# ?/, ""); print }' "$0" >&2 exit 1 fi regex="$1" shift # show all non-existing files given failed=0 for arg in "$@"; do if [ "${arg}" = "-" ]; then continue fi if [ ! -e "${arg}" ]; then printf "no file named \"%s\"\n" "${arg}" >&2 failed=1 fi done if [ "${failed}" -gt 0 ]; then exit 2 fi flush=0 if [ -p /dev/stdout ] || [ -t 1 ]; then flush=1 fi awk -v ci="${case_insensitive}" -v regex="${regex}" -v flush="${flush}" ' BEGIN { if (SUBSEP == "") SUBSEP = "\034" if (ci == 1 && IGNORECASE == "") { m = "your `awk` command lacks case-insensitive regex-matching" print(m) > "/dev/stderr" exit 125 } if (ci == 1) IGNORECASE = 1 } { k = match($0, regex) ? substr($0, RSTART, RLENGTH) : "" if (numkeys == 0) { first = k numkeys++ } # the first group is the only one which can be shown right away if (numkeys > 0 && k == first) { print if (flush) fflush() next } if (tally[k]++ == 0) ordkeys[++numkeys] = k groups[k SUBSEP tally[k]] = $0 } END { for (i = 2; i <= numkeys; i++) { k = ordkeys[i] n = tally[k] for (j = 1; j <= n; j++) print groups[k SUBSEP j] } } ' "$@"