#!/bin/sh # The MIT License (MIT) # # Copyright © 2025 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. # msort [option...] [regex...] [filenames...] # # Match 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 match the regex given case-insensitively # -ins match the regex given case-insensitively # -insensitive match the regex given case-insensitively # # -h show this help message # -help show this help message case "$1" in -h|--h|-help|--help) awk '/^# +msort /, /^$/ { 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 '/^# +msort /, /^$/ { gsub(/^# ?/, ""); print }' "$0" >&2 exit 1 fi regex="$1" shift command='awk' if [ -e /usr/bin/gawk ]; then command='gawk' fi # 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}" > /dev/stderr failed=1 fi done if [ "${failed}" -gt 0 ]; then exit 2 fi ${command} -v ci="${case_insensitive}" -v regex="${regex}" ' BEGIN { if (ci == 1 && IGNORECASE == "") { m = "your `awk` command lacks case-insensitive regex-matching" printf("\x1b[38;2;204;0;0m%s\x1b[0m\n", m) > "/dev/stderr" exit 125 } if (ci == 1) IGNORECASE = 1 } { k = match($0, regex) ? substr($0, RSTART, RLENGTH) : "" if (!(k in groups)) ordkeys[++oklen] = k groups[k][length(groups[k]) + 1] = $0 } END { for (i = 1; i <= oklen; i++) { k = ordkeys[i] n = length(groups[k]) for (j = 1; j <= n; j++) print groups[k][j] } } ' "$@"