File: clam.sh
   1 #!/bin/sh
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2025 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 # clam
  27 #
  28 # Command-Line Augmentation Module (clam): get the best out of your shell
  29 #
  30 #
  31 # This is a collection of arguably useful shell functions and shortcuts:
  32 # some of these extra commands can be real time/effort savers, ideally
  33 # letting you concentrate on getting things done.
  34 #
  35 # Some of these commands depend on my other scripts from the `pac-tools`,
  36 # others either rely on widely-preinstalled command-line apps, or ones
  37 # which are available on most of the major command-line `package` managers.
  38 #
  39 # To use this script, you're supposed to `source` it, so its definitions
  40 # stay for your whole shell session: for that, you can run `source clam` or
  41 # `. clam` (no quotes either way), either directly or at shell startup.
  42 #
  43 # This script is compatible with `bash`, `zsh`, and even `dash`, which is
  44 # debian linux's default non-interactive shell. Some of its commands even
  45 # seem to work on busybox's shell.
  46 
  47 
  48 case "$1" in
  49     -h|--h|-help|--help)
  50         # show help message, using the info-comment from this very script
  51         awk '
  52             /^case / { exit }
  53             /^# +clam$/, /^$/ { gsub(/^# ?/, ""); print }
  54         ' "$0"
  55         exit 0
  56     ;;
  57 esac
  58 
  59 
  60 # dash doesn't support regex-matching syntax, forcing to use case statements
  61 case "$0" in
  62     -bash|-dash|-sh|bash|dash|sh)
  63         # script is being sourced with bash or dash, which is good
  64         :
  65     ;;
  66     *)
  67         case "$ZSH_EVAL_CONTEXT" in
  68             *:file)
  69                 # script is being sourced with zsh, which is good
  70                 :
  71             ;;
  72             *)
  73                 # script is being run normally, which is a waste of time
  74         printf "\e[7mDon't run this script directly: instead source it\e[0m\n"
  75         printf "\e[7mby running '. clam' (without the single quotes).\e[0m\n"
  76                 # failing during shell-startup may deny shell access, so exit
  77                 # with a 0 error-code to declare success
  78                 exit 0
  79             ;;
  80         esac
  81     ;;
  82 esac
  83 
  84 
  85 alias 0=sbs
  86 alias 1='bsbs 1'
  87 alias 2='bsbs 2'
  88 alias 3='bsbs 3'
  89 alias 4='bsbs 4'
  90 alias 5='bsbs 5'
  91 alias 6='bsbs 6'
  92 alias 7='bsbs 7'
  93 alias 8='bsbs 8'
  94 alias 9='bsbs 9'
  95 alias lh1='less --header=1 -MKNiCRS'
  96 alias lh2='less --header=2 -MKNiCRS'
  97 alias lh3='less --header=3 -MKNiCRS'
  98 alias lh4='less --header=4 -MKNiCRS'
  99 alias lh5='less --header=5 -MKNiCRS'
 100 alias lh6='less --header=6 -MKNiCRS'
 101 alias lh7='less --header=7 -MKNiCRS'
 102 alias lh8='less --header=8 -MKNiCRS'
 103 alias lh9='less --header=9 -MKNiCRS'
 104 alias vh1='less --header=1 -MKiCRS'
 105 alias vh2='less --header=2 -MKiCRS'
 106 alias vh3='less --header=3 -MKiCRS'
 107 alias vh4='less --header=4 -MKiCRS'
 108 alias vh5='less --header=5 -MKiCRS'
 109 alias vh6='less --header=6 -MKiCRS'
 110 alias vh7='less --header=7 -MKiCRS'
 111 alias vh8='less --header=8 -MKiCRS'
 112 alias vh9='less --header=9 -MKiCRS'
 113 
 114 alias c=cat
 115 alias e=echo
 116 alias r='tput reset'
 117 
 118 # AWK in PARagraph-input mode
 119 alias awkpar=awkblock
 120 
 121 # Better Less runs `less`, showing line numbers, among other settings
 122 alias bl='less -MKNiCRS'
 123 
 124 # Better LESS runs `less`, showing line numbers, among other settings
 125 alias bless='less -MKNiCRS'
 126 
 127 # Breathe Lines 5: separate groups of 5 lines with empty lines
 128 alias bl5=b5
 129 
 130 # Book-like MANual, lays out `man` docs as pairs of side-by-side pages; uses
 131 # my tool `bsbs`
 132 alias bman=bookman
 133 
 134 # Better Units
 135 alias bu=bunits
 136 
 137 # load/concatenate BYTES from named data sources; uses my tool `get`
 138 alias bytes=get
 139 
 140 # Compile C Optimized
 141 alias cco='cc -Wall -O2 -s -march=native -mtune=native -flto'
 142 
 143 # Color DMESG
 144 alias cdmesg='dmesg --color=always'
 145 
 146 # Colored Json Query runs the `jq` app, allowing an optional filepath as the
 147 # data source, and even an optional transformation formula
 148 alias cjq='jq -C'
 149 
 150 # CLear Screen
 151 alias cls='tput reset'
 152 
 153 # Compile C Plus Plus Optimized
 154 alias cppo='c++ -Wall -O2 -s -march=native -mtune=native -flto'
 155 
 156 # Colored RipGrep ensures app `rg` emits colors when piped
 157 alias crg='rg --line-buffered --color=always'
 158 
 159 # CURL Silent spares you the progress bar, but still tells you about errors
 160 alias curls='curl --silent --show-error'
 161 
 162 # dictionary-DEFine the word given, using an online service
 163 alias def=define
 164 
 165 # turn JSON Lines into a proper json array
 166 alias dejsonl='jq -s -M'
 167 
 168 # turn UTF-16 data into UTF-8
 169 alias deutf16='iconv -f utf16 -t utf8'
 170 
 171 # edit plain-text files
 172 alias edit=micro
 173 
 174 # ENV with 0/null-terminated lines on stdout
 175 alias env0='env -0'
 176 
 177 # ENV Change folder, runs the command given in the folder given (first)
 178 alias envc='env -C'
 179 
 180 # Extended Plain Interactive Grep
 181 alias epig='ugrep --color=never -Q -E'
 182 
 183 # Editor Read-Only
 184 alias ero='micro -readonly true'
 185 
 186 # Expand 4 turns each tab into up to 4 spaces
 187 alias expand4='expand -t 4'
 188 
 189 # run the Fuzzy Finder (fzf) in multi-choice mode, with custom keybindings
 190 alias ff='fzf -m --bind ctrl-a:select-all,ctrl-space:toggle'
 191 
 192 # get FILE's MIME types
 193 alias filemime='file --mime-type'
 194 
 195 # run `gcc` with all optimizations on and with static analysis on
 196 alias gccmax='gcc -Wall -O2 -s -march=native -mtune=native -flto -fanalyzer'
 197 
 198 # hold stdout if used at the end of a pipe-chain
 199 alias hold='less -MKiCRS'
 200 
 201 # find all hyperlinks inside HREF attributes in the input text
 202 alias hrefs=href
 203 
 204 # make JSON Lines out of JSON data
 205 alias jl=jsonl
 206 
 207 # shrink/compact JSON using the `jq` app, allowing an optional filepath, and
 208 # even an optional transformation formula after that
 209 alias jq0='jq -c -M'
 210 
 211 # show JSON data on multiple lines, using 2 spaces for each indentation level,
 212 # allowing an optional filepath, and even an optional transformation formula
 213 # after that
 214 alias jq2='jq --indent 2 -M'
 215 
 216 # find the LAN (local-area network) IP address for this device
 217 alias lanip='hostname -I'
 218 
 219 # run `less`, showing line numbers, among other settings
 220 alias least='less -MKNiCRS'
 221 
 222 # Less with Header 1 runs `less` with line numbers, ANSI styles, without
 223 # line-wraps, and using the first line as a sticky-header, so it always
 224 # shows on top
 225 alias lh1='less --header=1 -MKNiCRS'
 226 
 227 # Less with Header 2 runs `less` with line numbers, ANSI styles, without
 228 # line-wraps, and using the first 2 lines as a sticky-header, so they
 229 # always show on top
 230 alias lh2='less --header=2 -MKNiCRS'
 231 
 232 # try to run the command given using line-buffering for its (standard) output
 233 alias livelines='stdbuf -oL'
 234 
 235 # LOAD data from the filename or URI given; uses my tool `get`
 236 alias load=get
 237 
 238 # LOcal SERver webserves files in a folder as localhost, using the port
 239 # number given, or port 8080 by default
 240 alias loser=serve
 241 
 242 # LOWercase all ASCII symbols
 243 alias low=tolower
 244 
 245 # LOWERcase all ASCII symbols
 246 alias lower=tolower
 247 
 248 # run `ls` showing how many 4k pages each file takes
 249 alias lspages='ls -s --block-size=4096'
 250 
 251 # Listen To Youtube
 252 alias lty=yap
 253 
 254 # MAKE IN folder
 255 alias makein=mif
 256 
 257 # Multi-Core MaKe runs `make` using all cores
 258 alias mcmk=mcmake
 259 
 260 # run `less`, showing line numbers, among other settings
 261 alias most='less -MKNiCRS'
 262 
 263 # emit nothing to output and/or discard everything from input
 264 alias nil=null
 265 
 266 # Nice Json Query colors JSON data using the `jq` app
 267 alias njq=cjq
 268 
 269 # Plain Interactive Grep
 270 alias pig='ugrep --color=never -Q -E'
 271 
 272 # Plain RipGrep
 273 alias prg='rg --line-buffered --color=never'
 274 
 275 # Quick Compile C Optimized
 276 alias qcco='cc -Wall -O2 -s -march=native -mtune=native -flto'
 277 
 278 # Quick Compile C Plus Plus Optimized
 279 alias qcppo='c++ -Wall -O2 -s -march=native -mtune=native -flto'
 280 
 281 # Run In Folder
 282 alias rif='env -C'
 283 
 284 # Read-Only Editor
 285 alias roe='micro -readonly true'
 286 
 287 # Read-Only Micro (text editor)
 288 alias rom='micro -readonly true'
 289 
 290 # Read-Only Top
 291 alias rot='htop --readonly'
 292 
 293 # RUN IN folder
 294 alias runin='env -C'
 295 
 296 # place lines Side-By-Side
 297 # alias sbs=column
 298 
 299 # Silent CURL spares you the progress bar, but still tells you about errors
 300 alias scurl='curl --silent --show-error'
 301 
 302 # Stdbuf Output Line-buffered
 303 alias sol='stdbuf -oL'
 304 
 305 # TRY running a command, showing its outcome/error-code on failure
 306 alias try=verdict
 307 
 308 # Time Verbosely the command given
 309 alias tv='/usr/bin/time -v'
 310 
 311 # VERTical REVert emits lines in reverse order of appearance
 312 alias vertrev=tac
 313 
 314 # emit lines in reverse order of appearance
 315 alias upsidedown=tac
 316 
 317 # run `cppcheck` with even stricter options
 318 alias vetc='cppcheck --enable=portability,style --check-level=exhaustive'
 319 
 320 # run `cppcheck` with even stricter options, also checking for c89 compliance
 321 alias vetc89='cppcheck --enable=portability,style --check-level=exhaustive --std=c89'
 322 
 323 # run `cppcheck` with even stricter options
 324 alias vetcpp='cppcheck --enable=portability,style --check-level=exhaustive'
 325 
 326 # VET SHell scripts
 327 alias vetsh=vetshell
 328 
 329 # check shell scripts for common gotchas, avoiding complaints about using
 330 # the `local` keyword, which is widely supported in practice
 331 alias vetshell='shellcheck -e 3043'
 332 
 333 # View with Header 1 runs `less` without line numbers, ANSI styles, without
 334 # line-wraps, and using the first line as a sticky-header, so it always shows
 335 # on top
 336 alias vh1='less --header=1 -MKiCRS'
 337 
 338 # View with Header 2 runs `less` without line numbers, ANSI styles, without
 339 # line-wraps, and using the first 2 lines as sticky-headers, so they always
 340 # show on top
 341 alias vh2='less --header=2 -MKiCRS'
 342 
 343 # run a command using an empty environment
 344 alias void='env -i'
 345 
 346 # turn plain-text from latin-1 into UTF-8; the name is from `vulgarization`,
 347 # which is the mutation of languages away from latin during the middle ages
 348 alias vulgarize='iconv -f latin-1 -t utf-8'
 349 
 350 # recursively find all files with trailing spaces/CRs
 351 alias wheretrails=whichtrails
 352 
 353 # run `xargs`, using zero/null bytes as the extra-arguments terminator
 354 alias x0='xargs -0'
 355 
 356 # Xargs Lines, runs `xargs` using whole lines as extra arguments
 357 alias xl=xargsl
 358 
 359 # find name from the local `apt` database of installable packages
 360 aptfind() {
 361     local arg
 362     local gap=0
 363     local options='-MKiCRS'
 364 
 365     if [ $# -eq 1 ]; then
 366         options='--header=1 -MKiCRS'
 367     fi
 368 
 369     for arg in "$@"; do
 370         [ "${gap}" -gt 0 ] && printf "\n"
 371         gap=1
 372         printf "\e[7m%-80s\e[0m\n\n" "${arg}"
 373 
 374         # despite warnings, the `search` command has been around for years
 375         apt search "${arg}" 2> /dev/null |
 376             grep -E -A 1 "^[a-z0-9-]*${arg}" | sed -u 's/^--$//'
 377     done | less ${options}
 378 }
 379 
 380 # APT UPdate/grade
 381 aptup() { sudo apt update && sudo apt upgrade "$@"; sudo -k; }
 382 
 383 # emit each argument given as its own line of output
 384 # args() {
 385 #     awk 'BEGIN { for (i = 1; i < ARGC; i++) print ARGV[i]; exit }' "$@"
 386 # }
 387 
 388 # emit each argument given as its own line of output
 389 args() { printf "%s\n" "$@"; }
 390 
 391 # AWK in BLOCK/paragraph-input mode
 392 awkblock() {
 393     if [ -p /dev/stdout ] || [ -t 1 ]; then
 394         stdbuf -oL awk -F='' -v RS='' "$@"
 395     else
 396         awk -F='' -v RS='' "$@"
 397     fi
 398 }
 399 
 400 # AWK in TSV input/output mode
 401 awktsv() {
 402     if [ -p /dev/stdout ] || [ -t 1 ]; then
 403         stdbuf -oL awk -F "\t" -v OFS="\t" "$@"
 404     else
 405         awk -F "\t" -v OFS="\t" "$@"
 406     fi
 407 }
 408 
 409 # Breathe lines 5: separate groups of 5 lines with empty lines
 410 b5() {
 411     if [ -p /dev/stdout ] || [ -t 1 ]; then
 412         stdbuf -oL awk 'NR % 5 == 1 && NR != 1 { print "" } 1' "$@"
 413     else
 414         awk 'NR % 5 == 1 && NR != 1 { print "" } 1' "$@"
 415     fi
 416 }
 417 
 418 # show an ansi-styled BANNER-like line
 419 banner() { printf "\e[7m%-$(tput cols)s\e[0m\n" "$*"; }
 420 
 421 # emit a colored bar which can help visually separate different outputs
 422 bar() {
 423     [ "${1:-80}" -gt 0 ] && printf "\e[48;2;218;218;218m%${1:-80}s\e[0m\n" ""
 424 }
 425 
 426 # Bullets with AWK shows a reverse-sorted tally of all lines read, where ties
 427 # are sorted alphabetically, and where trailing bullets are added to quickly
 428 # make the tally counts comparable at a glance
 429 bawk() {
 430     local code="${1:-\$0}"
 431     [ $# -gt 0 ] && shift
 432 
 433     printf "value\ttally\tbullets\n"
 434     awk '
 435         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
 436         { low = lower = tolower($0) }
 437         { tally['"${code}"']++ }
 438 
 439         END {
 440             # find the max tally, which is needed to build the bullets-string
 441             max = 0
 442             for (k in tally) {
 443                 if (max < tally[k]) max = tally[k]
 444             }
 445 
 446             # make enough bullets for all tallies: this loop makes growing the
 447             # string a task with complexity O(n * log n), instead of a naive
 448             # O(n**2), which can slow-down things when tallies are high enough
 449             bullets = "•"
 450             for (n = max; n > 1; n /= 2) {
 451                 bullets = bullets bullets
 452             }
 453 
 454             # emit unsorted output lines to the sort cmd, which will emit the
 455             # final reverse-sorted tally lines
 456             for (k in tally) {
 457                 s = substr(bullets, 1, tally[k])
 458                 printf "%s\t%d\t%s\n", k, tally[k], s
 459             }
 460         }
 461     ' "$@" | sort -t "$(printf "\t")" -rnk2 -k1d
 462 }
 463 
 464 # play a repeating and annoying high-pitched beep sound a few times a second,
 465 # lasting the number of seconds given, or for 1 second by default; uses my
 466 # script `sboard`
 467 beeps() { sboard beeps "${1:-1}" "${2:-1}"; }
 468 
 469 # play a repeating synthetic-bell-like sound lasting the number of seconds
 470 # given, or for 1 second by default; uses my tool `sboard`
 471 bell() { sboard bell "${1:-1}" "${2:-1}"; }
 472 
 473 # Breathe Header 5: add an empty line after the first one (the header),
 474 # then separate groups of 5 lines with empty lines between them
 475 bh5() {
 476     if [ -p /dev/stdout ] || [ -t 1 ]; then
 477         stdbuf -oL awk '(NR - 1) % 5 == 1 { print "" } 1' "$@"
 478     else
 479         awk '(NR - 1) % 5 == 1 { print "" } 1' "$@"
 480     fi
 481 }
 482 
 483 # emit a line with a repeating block-like symbol in it
 484 blocks() { [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" "" | sed 's- -█-g'; }
 485 
 486 # BOOK-like MANual, lays out `man` docs as pairs of side-by-side pages; uses
 487 # my tool `bsbs`
 488 bookman() {
 489     local w
 490     w="$(tput cols)"
 491     w="$((w / 2 - 4))"
 492     if [ "$w" -lt 65 ]; then
 493         w=65
 494     fi
 495     MANWIDTH="$w" man "$@" | bsbs 2
 496 }
 497 
 498 # split lines using the separator given, turning them into single-item lines
 499 breakdown() {
 500     local sep="${1:- }"
 501     [ $# -gt 0 ] && shift
 502     local command='awk'
 503     if [ -p /dev/stdout ] || [ -t 1 ]; then
 504         command='stdbuf -oL awk'
 505     fi
 506 
 507     ${command} -F "${sep}" '{ for (i = 1; i <= NF; i++) print $i }' "$@"
 508 }
 509 
 510 # Better UNITS
 511 bunits() {
 512     case "$2" in
 513         ac|acre|acres) units -v -H '' "$1 acres" kilometers^2;;
 514         cup|cups) units -v -H '' "$1 cups" liters;;
 515         deg|degs|degree|degrees) units -v -H '' "$1 degrees" radians;;
 516         f|fahr*) units -v -H '' "tempF($1)" tempC;;
 517         floz) units -v -H '' "$1 floz" milliliters;;
 518         ft|feet|foot) units -v -H '' "$1 feet" meters;;
 519         ft2|ft^2|sqft|sqfeet) units -v -H '' "$1 ft^2" meters^2;;
 520         ft3|ft^3|cuft|cufeet) units -v -H '' "$1 ft^3" meters^3;;
 521         gal|gallon|gals|gallons) units -v -H '' "$1 gallons" liters;;
 522         gb|gib|gibi|gibibytes) units -v -H '' "$1 gibibytes" bytes;;
 523         in|inch|inches) units -v -H '' "$1 inches" centimeters;;
 524         kb|kib|kibi|kibibytes) units -v -H '' "$1 kibibytes" bytes;;
 525         lb|lbs|pound|pounds) units -v -H '' "$1 pounds" kilograms;;
 526         mb|mib|mibi|mibibytes) units -v -H '' "$1 mibibytes" bytes;;
 527         mi|mile|miles) units -v -H '' "$1 miles" kilometers;;
 528         mi2|mi^2|miles^2) units -v -H '' "$1 mi^2" kilometers^2;;
 529         mi3|mi^3|miles^3) units -v -H '' "$1 mi^3" kilometers^3;;
 530         mph) units -v -H '' "$1 mph" kph;;
 531         nmi|nmile|nmiles) units -v -H '' "$1 nmi" kilometers;;
 532         nmi2|nmi^2|nmile^2|nmiles^2) units -v -H '' "$1 nmi^2" kilometers^2;;
 533         oz|ozs|ounce|ounces) units -v -H '' "$1 ounces" grams;;
 534         pt|pts|pint|pints|uspint|uspints) units -v -H '' "$1 uspints" liters;;
 535         tb|tib|tibi|tibibytes) units -v -H '' "$1 tibibytes" bytes;;
 536         yd|yds|yard|yards) units -v -H '' "$1 yards" meters;;
 537         yd^2|yds^2|yard^2|yards^2) units -v -H '' "$1 yards^2" meters^2;;
 538         *) units -v -H '' "$@";;
 539     esac
 540 }
 541 
 542 # play a busy-phone-line sound lasting the number of seconds given, or for 1
 543 # second by default; uses my tool `sboard`
 544 busy() { sboard busy "${1:-1}" "${2:-1}"; }
 545 
 546 # CAlculator with Nice numbers runs my tool `ca` and colors results with
 547 # my tool `nn`, alternating styles to make long numbers easier to read
 548 can() {
 549     local arg
 550     for arg in "$@"; do
 551         ca "${arg}"
 552     done | nn --gray
 553 }
 554 
 555 # uppercase the first letter on each line, and lowercase all later letters
 556 capitalize() { sed -E -u 's-^(.*)-\L\1-; s-^(.)-\u\1-'; }
 557 
 558 # Count with AWK: count the times the AWK expression/condition given is true
 559 cawk() {
 560     local cond="${1:-1}"
 561     [ $# -gt 0 ] && shift
 562     awk '
 563         BEGIN { count = c = 0 }
 564         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
 565         { low = lower = tolower($0) }
 566         '"${cond}"' { count++; c = count }
 567         END { print count }
 568     ' "$@"
 569 }
 570 
 571 # center-align lines of text, using the current screen width
 572 center() {
 573     local command='awk'
 574     if [ -e /usr/bin/gawk ]; then
 575         command='gawk'
 576     fi
 577 
 578     ${command} -v width="$(tput cols)" '
 579         {
 580             gsub(/\r$/, "")
 581             lines[NR] = $0
 582             s = $0
 583             gsub(/\x1b\[[0-9;]*[A-Za-z]/, "", s) # ANSI style-changers
 584             l = length(s)
 585             if (maxlen < l) maxlen = l
 586         }
 587 
 588         END {
 589             n = (width - maxlen) / 2
 590             if (n % 1) n = n - (n % 1)
 591             fmt = sprintf("%%%ds%%s\n", (n > 0) ? n : 0)
 592             for (i = 1; i <= NR; i++) printf fmt, "", lines[i]
 593         }
 594     ' "$@"
 595 }
 596 
 597 # Color file-EXTensions, or any substring which looks like one
 598 cext() {
 599     local command='awk'
 600     if [ -p /dev/stdout ] || [ -t 1 ]; then
 601         command='stdbuf -oL awk'
 602     fi
 603 
 604     ${command} '
 605         BEGIN {
 606             palette[n++] = "\x1b[38;2;0;95;215m" # blue
 607             palette[n++] = "\x1b[38;2;215;95;0m" # orange
 608             palette[n++] = "\x1b[38;2;135;95;255m" # purple
 609             palette[n++] = "\x1b[38;2;0;175;215m" # cyan
 610             palette[n++] = "\x1b[38;2;255;135;255m" # pink
 611             palette[n++] = "\x1b[38;2;0;135;95m" # green
 612             palette[n++] = "\x1b[38;2;204;0;0m" # red
 613             palette[n++] = "\x1b[38;2;168;168;168m" # gray
 614             palcount = length(palette)
 615             n = 0
 616         }
 617 
 618         {
 619             # ignore cursor-movers and style-changers
 620             # gsub(/\x1b\[[0-9;]*[A-Za-z]/, "")
 621 
 622             rest = $0
 623 
 624             while (match(rest, /\.[A-Za-z][A-Za-z0-9_-]*/)) {
 625                 printf "%s", substr(rest, 1, RSTART - 1)
 626 
 627                 ext = substr(rest, RSTART, RLENGTH)
 628                 rest = substr(rest, RSTART + RLENGTH)
 629 
 630                 style = ext2style[ext]
 631                 if (style == "") {
 632                     style = palette[n % palcount]
 633                     ext2style[ext] = style
 634                     n++
 635                 }
 636 
 637                 printf "%s%s\x1b[0m", style, ext
 638             }
 639 
 640             print rest
 641         }
 642     ' "$@"
 643 }
 644 
 645 # Colored Go Test on the folder given; uses my command `jawk`
 646 cgt() { go test "${1:-.}" 2>&1 | jawk '/^ok/' '/^[-]* ?FAIL/' '/^\?/'; }
 647 
 648 # Compile Rust Optimized
 649 cro() {
 650     rustc -C lto=true -C codegen-units=1 -C debuginfo=0 -C strip=symbols \
 651         -C opt-level=3 "$@"
 652 }
 653 
 654 # emit a line with a repeating cross-like symbol in it
 655 crosses() { [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" "" | sed 's- -×-g'; }
 656 
 657 # listen to streaming DANCE music
 658 dance() {
 659     printf "streaming \e[7mDance Wave Retro\e[0m\n"
 660     mpv --really-quiet https://retro.dancewave.online/retrodance.mp3
 661 }
 662 
 663 # emit a line with a repeating dash-like symbol in it
 664 dashes() { [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" "" | sed 's- -—-g'; }
 665 
 666 # remove commas in numbers, as well as leading dollar signs in numbers
 667 decomma() {
 668     sed -E 's-([0-9]{3}),-\1-g; s-([0-9]{1,2}),-\1-g; s-\$([0-9\.]+)-\1-g'
 669 }
 670 
 671 # remove indentations from lines
 672 dedent() {
 673     awk '
 674         { lines[NR] = $0 }
 675         { if (match($0, /^ +/) && (n == 0 || n > RLENGTH)) n = RLENGTH }
 676         END { for (i = 1; i <= NR; i++) print substr(lines[i], n + 1) }
 677     ' "$@"
 678 }
 679 
 680 dehtmlify() {
 681     local command='awk'
 682     if [ -p /dev/stdout ] || [ -t 1 ]; then
 683         command='stdbuf -oL awk'
 684     fi
 685 
 686     ${command} '
 687         {
 688             gsub(/<\/?[^>]+>/, "")
 689             gsub(/&amp;/, "&")
 690             gsub(/&lt;/, "<")
 691             gsub(/&gt;/, ">")
 692             gsub(/^ +| *\r?$/, "")
 693             gsub(/  +/, " ")
 694             print
 695         }
 696     ' "$@"
 697 }
 698 
 699 # expand tabs each into up to the number of space given, or 4 by default
 700 detab() {
 701     local tabstop="${1:-4}"
 702     [ $# -gt 0 ] && shift
 703     if [ -p /dev/stdout ] || [ -t 1 ]; then
 704         stdbuf -oL expand -t "${tabstop}" "$@"
 705     else
 706         expand -t "${tabstop}" "$@"
 707     fi
 708 }
 709 
 710 # DIVide 2 numbers 3 ways, including the complement
 711 div() {
 712     awk -v a="${1:-1}" -v b="${2:-1}" '
 713         BEGIN {
 714             gsub(/_/, "", a)
 715             gsub(/_/, "", b)
 716             if (a > b) { c = a; a = b; b = c }
 717             c = 1 - a / b
 718             if (0 <= c && c <= 1) printf "%f\n%f\n%f\n", a / b, b / a, c
 719             else printf "%f\n%f\n", a / b, b / a
 720             exit
 721         }'
 722 }
 723 
 724 # get/fetch data from the filename or URI given; named `dog` because dogs can
 725 # `fetch` things for you
 726 dog() {
 727     if [ $# -gt 1 ]; then
 728         printf "\e[31mdogs only have 1 mouth to fetch with\e[0m\n" >&2
 729         return 1
 730     fi
 731 
 732     if [ -e "$1" ]; then
 733         if [ -p /dev/stdout ] || [ -t 1 ]; then stdbuf -oL cat "$1"; else cat "$1"; fi
 734         return $?
 735     fi
 736 
 737     case "${1:--}" in
 738         -) if [ -p /dev/stdout ] || [ -t 1 ]; then stdbuf -oL cat -; else cat -; fi;;
 739         file://*|https://*|http://*) curl --show-error -s "$1";;
 740         ftp://*|ftps://*|sftp://*) curl --show-error -s "$1";;
 741         dict://*) curl --show-error -s "$1";;
 742         *) curl --show-error -s "https://$1";;
 743     esac 2> /dev/null || {
 744         printf "\e[31mcan't fetch %s\e[0m\n" "${1:--}" >&2
 745         return 1
 746     }
 747 }
 748 
 749 # emit a line with a repeating dot-like symbol in it
 750 dots() { [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" "" | sed 's- -·-g'; }
 751 
 752 # show the current Date and Time
 753 dt() {
 754     printf "\e[38;2;78;154;6m%s\e[0m  \e[38;2;52;101;164m%s\e[0m\n" \
 755         "$(date +'%a %b %d')" "$(date +%T)"
 756 }
 757 
 758 # show the current Date, Time, and a Calendar with the 3 `current` months
 759 dtc() {
 760     {
 761         # show the current date/time center-aligned
 762         printf "%20s\e[38;2;78;154;6m%s\e[0m  \e[38;2;52;101;164m%s\e[0m\n\n" \
 763             "" "$(date +'%a %b %d')" "$(date +%T)"
 764         # debian linux has a different `cal` app which highlights the day
 765         if [ -e "/usr/bin/ncal" ]; then
 766             # fix debian/ncal's weird way to highlight the current day
 767             ncal -C -3 | sed -E 's/_\x08(.)/\x1b[7m\1\x1b[0m/g'
 768         else
 769             cal -3
 770         fi
 771     } | less -MKiCRS
 772 }
 773 
 774 # EDit RUN shell commands, using an interactive editor; uses my tool `leak`
 775 edrun() {
 776     # dash doesn't support the process-sub syntax
 777     # . <( micro -readonly true -filetype shell | leak --inv )
 778     micro -readonly true -filetype shell | leak --inv | . /dev/fd/0
 779 }
 780 
 781 # convert EURos into CAnadian Dollars, using the latest official exchange
 782 # rates from the bank of canada; during weekends, the latest rate may be
 783 # from a few days ago; the default amount of euros to convert is 1, when
 784 # not given
 785 eur2cad() {
 786     local site='https://www.bankofcanada.ca/valet/observations/group'
 787     local csv_rates="${site}/FX_RATES_DAILY/csv"
 788     local url="${csv_rates}?start_date=$(date -d '3 days ago' +'%Y-%m-%d')"
 789     curl -s "${url}" | awk -F, -v amount="$(echo "${1:-1}" | sed 's-_--g')" '
 790         /EUR/ { for (i = 1; i <= NF; i++) if($i ~ /EUR/) j = i }
 791         END { gsub(/"/, "", $j); if (j != 0) printf "%.2f\n", amount * $j }
 792     '
 793 }
 794 
 795 # fetch/web-request all URIs given, using protcol HTTPS when none is given
 796 fetch() {
 797     local arg
 798     for arg in "$@"; do
 799         case "${arg}" in
 800             file://*|https://*|http://*|ftp://*|ftps://*|sftp://*|dict://*)
 801                 curl --silent --show-error "${arg}";;
 802             *)
 803                 curl --silent --show-error "https://${arg}";;
 804         esac
 805     done
 806 }
 807 
 808 # get the first n lines, or 1 by default
 809 first() { head -n "${1:-1}" "${2:--}"; }
 810 
 811 # Field-Names AWK remembers field-positions by name, from the first input line
 812 fnawk() {
 813     local code="${1:-1}"
 814     [ $# -gt 0 ] && shift
 815 
 816     local buffering=''
 817     if [ -p /dev/stdout ] || [ -t 1 ]; then
 818         buffering='stdbuf -oL'
 819     fi
 820 
 821     ${buffering} awk -v OFS="\t" '
 822         NR == 1 {
 823             FS = /\t/ ? "\t" : " "
 824             $0 = $0
 825             for (i = 1; i <= NF; i++) names[$i] = i
 826             i = ""
 827         }
 828         { low = lower = tolower($0) }
 829         '"${code}"'
 830     ' "$@"
 831 }
 832 
 833 # start from the line number given, skipping all previous ones
 834 fromline() { tail -n +"${1:-1}" "${2:--}"; }
 835 
 836 # convert a mix of FeeT and INches into meters
 837 ftin() {
 838     local ft="${1:-0}"
 839     ft="$(echo "${ft}" | sed 's-_--g')"
 840     local in="${2:-0}"
 841     in="$(echo "${in}" | sed 's-_--g')"
 842     awk "BEGIN { print 0.3048 * ${ft} + 0.0254 * ${in}; exit }"
 843 }
 844 
 845 # Gawk Bignum Print
 846 gbp() { gawk --bignum "BEGIN { print $1; exit }"; }
 847 
 848 # glue/stick together various lines, only emitting a line-feed at the end; an
 849 # optional argument is the output-item-separator, which is empty by default
 850 glue() {
 851     local sep="${1:-}"
 852     [ $# -gt 0 ] && shift
 853     awk -v sep="${sep}" '
 854         NR > 1 { printf "%s", sep }
 855         { gsub(/\r/, ""); printf "%s", $0 }
 856         END { if (NR > 0) print "" }
 857     ' "$@"
 858 }
 859 
 860 # GO Build Stripped: a common use-case for the go compiler
 861 gobs() { go build -ldflags "-s -w" -trimpath "$@"; }
 862 
 863 # GO DEPendencieS: show all dependencies in a go project
 864 godeps() { go list -f '{{ join .Deps "\n" }}' "$@"; }
 865 
 866 # GO IMPortS: show all imports in a go project
 867 goimps() { go list -f '{{ join .Imports "\n" }}' "$@"; }
 868 
 869 # go to the folder picked using an interactive TUI; uses my tool `bf`
 870 goto() {
 871     local where
 872     where="$(bf "${1:-.}")"
 873     if [ $? -ne 0 ]; then
 874         return 0
 875     fi
 876 
 877     where="$(realpath "${where}")"
 878     if [ ! -d "${where}" ]; then
 879         where="$(dirname "${where}")"
 880     fi
 881     cd "${where}" || return
 882 }
 883 
 884 # GRoup via AWK groups lines using common results of the AWK expression given
 885 grawk() {
 886     local code="${1:-\$0}"
 887     [ $# -gt 0 ] && shift
 888 
 889     local command='awk'
 890     if [ -p /dev/stdout ] || [ -t 1 ]; then
 891         command='stdbuf -oL awk'
 892     fi
 893 
 894     ${command} '
 895         function maybe(x, y) {
 896             if (y == "") { y = x; x = $0 }
 897             return match(x, y) ? substr(x, RSTART, RLENGTH) : ""
 898         }
 899 
 900         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
 901         { low = lower = tolower($0) }
 902 
 903         {
 904             k = ('"${code}"')
 905             if (!(k in groups)) ordkeys[++oklen] = k
 906             groups[k][length(groups[k]) + 1] = $0
 907         }
 908 
 909         END {
 910             for (i = 1; i <= oklen; i++) {
 911                 k = ordkeys[i]
 912                 n = length(groups[k])
 913                 for (j = 1; j <= n; j++) print groups[k][j]
 914             }
 915         }
 916     ' "$@"
 917 }
 918 
 919 # Global extended regex SUBstitute, using the AWK function of the same name:
 920 # arguments are used as regex/replacement pairs, in that order
 921 gsub() {
 922     local command='awk'
 923     if [ -p /dev/stdout ] || [ -t 1 ]; then
 924         command='stdbuf -oL awk'
 925     fi
 926 
 927     ${command} '
 928         BEGIN {
 929             for (i = 1; i < ARGC; i++) {
 930                 args[++n] = ARGV[i]
 931                 delete ARGV[i]
 932             }
 933         }
 934 
 935         {
 936             for (i = 1; i <= n; i += 2) gsub(args[i], args[i + 1])
 937             print
 938         }
 939     ' "$@"
 940 }
 941 
 942 # show Help laid out on 2 side-by-side columns; uses my tool `bsbs`
 943 h2() { naman "$@" | bsbs 2; }
 944 
 945 # play a heartbeat-like sound lasting the number of seconds given, or for 1
 946 # second by default; uses my tool `sboard`
 947 heartbeat() { sboard heartbeat "${1:-1}" "${2:-1}"; }
 948 
 949 # Highlighted-style ECHO
 950 hecho() { printf "\e[7m%s\e[0m\n" "$*"; }
 951 
 952 # show each byte as a pair of HEXadecimal (base-16) symbols
 953 hexify() {
 954     cat "$@" | od -x -A n |
 955         awk '{ gsub(/ +/, ""); printf "%s", $0 } END { printf "\n" }'
 956 }
 957 
 958 # Help Me Remember my custom shell commands
 959 hmr() {
 960     local cmd="bat"
 961     # debian linux uses a different name for the `bat` app
 962     if [ -e "/usr/bin/batcat" ]; then
 963         cmd="batcat"
 964     fi
 965 
 966     "$cmd" \
 967         --style=plain,header,numbers --theme='Monokai Extended Light' \
 968         --wrap=never --color=always "$(which clam)" |
 969             sed -e 's-\x1b\[38;5;70m-\x1b[38;5;28m-g' \
 970                 -e 's-\x1b\[38;5;214m-\x1b[38;5;208m-g' \
 971                 -e 's-\x1b\[38;5;243m-\x1b[38;5;103m-g' \
 972                 -e 's-\x1b\[38;5;238m-\x1b[38;5;245m-g' \
 973                 -e 's-\x1b\[38;5;228m-\x1b[48;5;228m-g' |
 974                 less -MKiCRS
 975 }
 976 
 977 # convert seconds into a colon-separated Hours-Minutes-Seconds triple
 978 hms() {
 979     echo "${@:-0}" | sed -E 's-_--g; s- +-\n-g' | awk '/./ {
 980         x = $0
 981         h = (x - x % 3600) / 3600
 982         m = (x % 3600) / 60
 983         s = x % 60
 984         printf "%02d:%02d:%05.2f\n", h, m, s
 985     }'
 986 }
 987 
 988 # find all hyperlinks inside HREF attributes in the input text
 989 href() {
 990     local arg
 991     for arg in "${@:--}"; do
 992         grep --line-buffered -E -o 'href="[^"]+"' "${arg}"
 993     done | sed -u 's-^href="--; s-"$--'
 994 }
 995 
 996 # avoid/ignore lines which case-insensitively match any of the regexes given
 997 iavoid() {
 998     local command='awk'
 999     if [ -p /dev/stdout ] || [ -t 1 ]; then
1000         command='stdbuf -oL awk'
1001     fi
1002 
1003     ${command} '
1004         BEGIN {
1005             if (IGNORECASE == "") {
1006                 m = "this variant of AWK lacks case-insensitive regex-matching"
1007                 print(m) > "/dev/stderr"
1008                 exit 125
1009             }
1010             IGNORECASE = 1
1011 
1012             for (i = 1; i < ARGC; i++) {
1013                 e[i] = ARGV[i]
1014                 delete ARGV[i]
1015             }
1016         }
1017 
1018         {
1019             for (i = 1; i < ARGC; i++) if ($0 ~ e[i]) next
1020             print
1021             got++
1022         }
1023 
1024         END { exit(got == 0) }
1025     ' "${@:-^\r?$}"
1026 }
1027 
1028 # ignore command in a pipe: this allows quick re-editing of pipes, while
1029 # still leaving signs of previously-used steps, as a memo
1030 idem() { cat; }
1031 
1032 # ignore command in a pipe: this allows quick re-editing of pipes, while
1033 # still leaving signs of previously-used steps, as a memo
1034 ignore() { cat; }
1035 
1036 # only keep lines which case-insensitively match any of the regexes given
1037 imatch() {
1038     local command='awk'
1039     if [ -p /dev/stdout ] || [ -t 1 ]; then
1040         command='stdbuf -oL awk'
1041     fi
1042 
1043     ${command} '
1044         BEGIN {
1045             if (IGNORECASE == "") {
1046                 m = "this variant of AWK lacks case-insensitive regex-matching"
1047                 print(m) > "/dev/stderr"
1048                 exit 125
1049             }
1050             IGNORECASE = 1
1051 
1052             for (i = 1; i < ARGC; i++) {
1053                 e[i] = ARGV[i]
1054                 delete ARGV[i]
1055             }
1056         }
1057 
1058         {
1059             for (i = 1; i < ARGC; i++) {
1060                 if ($0 ~ e[i]) {
1061                     print
1062                     got++
1063                     next
1064                 }
1065             }
1066         }
1067 
1068         END { exit(got == 0) }
1069     ' "${@:-[^\r]}"
1070 }
1071 
1072 # start each non-empty line with extra n spaces
1073 indent() {
1074     local command='awk'
1075     if [ -p /dev/stdout ] || [ -t 1 ]; then
1076         command='stdbuf -oL awk'
1077     fi
1078 
1079     ${command} '
1080         BEGIN {
1081             n = ARGV[1] + 0
1082             delete ARGV[1]
1083             fmt = sprintf("%%%ds%%s\n", (n > 0) ? n : 0)
1084         }
1085 
1086         /^\r?$/ { print ""; next }
1087         { gsub(/\r$/, ""); printf(fmt, "", $0) }
1088     ' "$@"
1089 }
1090 
1091 # emit each word-like item from each input line on its own line; when a file
1092 # has tabs on its first line, items are split using tabs alone, which allows
1093 # items to have spaces in them
1094 items() {
1095     local command='awk'
1096     if [ -p /dev/stdout ] || [ -t 1 ]; then
1097         command='stdbuf -oL awk'
1098     fi
1099 
1100     ${command} '
1101         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1102         { gsub(/\r$/, ""); for (i = 1; i <= NF; i++) print $i }
1103     ' "$@"
1104 }
1105 
1106 # Judge with AWK colors lines using up to 3 (optional) AWK conditions, namely
1107 # `good` (green), `bad` (red), and `meh` (gray)
1108 jawk() {
1109     local code="${1:-\$0}"
1110     [ $# -gt 0 ] && shift
1111 
1112     local command='awk'
1113     if [ -p /dev/stdout ] || [ -t 1 ]; then
1114         command='stdbuf -oL awk'
1115     fi
1116 
1117     local good="${1:-0}"
1118     local bad="${2:-0}"
1119     local meh="${3:-0}"
1120 
1121     [ $# -gt 0 ] && shift
1122     [ $# -gt 0 ] && shift
1123     [ $# -gt 0 ] && shift
1124 
1125     ${command} '
1126         BEGIN {
1127             # normal good-style is green, colorblind-friendly good-style is blue
1128             cb = ENVIRON["COLORBLIND"] != 0 || ENVIRON["COLOR_BLIND"] != 0
1129             good_style = cb ? "\x1b[38;2;0;95;215m" : "\x1b[38;2;0;135;95m"
1130             good_fmt = good_style "%s\x1b[0m\n"
1131             good_reset = "\x1b[0m" good_style
1132         }
1133 
1134         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1135         { low = lower = tolower($0) }
1136 
1137         '"${good}"' {
1138             gsub(/\x1b\[0m/, good_reset)
1139             printf good_fmt, $0
1140             next
1141         }
1142 
1143         '"${bad}"' {
1144             gsub(/\x1b\[0m/, "\x1b[0m\x1b[38;2;204;0;0m")
1145             printf "\x1b[38;2;204;0;0m%s\x1b[0m\n", $0
1146             next
1147         }
1148 
1149         '"${meh}"' {
1150             gsub(/\x1b\[0m/, "\x1b[0m\x1b[38;2;168;168;168m")
1151             printf "\x1b[38;2;168;168;168m%s\x1b[0m\n", $0
1152             next
1153         }
1154 
1155         1
1156     ' "$@"
1157 }
1158 
1159 # listen to streaming JAZZ music
1160 jazz() {
1161     printf "streaming \e[7mSmooth Jazz Instrumental\e[0m\n"
1162     mpv --quiet https://stream.zeno.fm/00rt0rdm7k8uv
1163 }
1164 
1165 # show a `dad` JOKE from the web, sometimes even a very funny one
1166 joke() {
1167     curl --silent --show-error https://icanhazdadjoke.com | fold -s |
1168         awk '{ gsub(/ *\r?$/, ""); print }'
1169 }
1170 
1171 # JSON Query Lines turns JSON top-level arrays into multiple individually-JSON
1172 # lines using the `jq` app, keeping all other top-level values as single line
1173 # JSON outputs
1174 jql() {
1175     local code="${1:-.}"
1176     [ $# -gt 0 ] && shift
1177     jq -c -M "${code} | .[]" "$@"
1178 }
1179 
1180 # JSON Query Keys runs `jq` to find all unique key-combos from tabular JSON
1181 jqk() {
1182     local code="${1:-.}"
1183     [ $# -gt 0 ] && shift
1184     jq -c -M "${code} | .[] | keys" "$@" | awk '!c[$0]++'
1185 }
1186 
1187 # JSON Keys finds all unique key-combos from tabular JSON data; uses my tools
1188 # `jsonl` and `zj`
1189 # jsonk() { cat "${1:--}" | zj . .keys | jsonl | awk '!c[$0]++'; }
1190 
1191 # JSON Keys finds all unique key-combos from tabular JSON data; uses my tools
1192 # `jsonl` and `tjp`
1193 jsonk() {
1194     tjp '[e.keys() for e in v] if isinstance(v, (list, tuple)) else v.keys()' \
1195         "${1:--}" | jsonl | awk '!c[$0]++'
1196 }
1197 
1198 # JSON Table, turns TSV tables into tabular JSON, where valid-JSON values are
1199 # auto-parsed into numbers, booleans, etc...; uses my tools `jsons` and `tjp`
1200 jsont() {
1201     jsons "$@" | tjp \
1202         '[{k: rescue(lambda: loads(v), v) for k, v in e.items()} for e in v]'
1203 }
1204 
1205 # emit the given number of random/junk bytes, or 1024 junk bytes by default
1206 junk() { head -c "$(echo "${1:-1024}" | sed 's-_--g')" /dev/urandom; }
1207 
1208 # play a stereotypical once-a-second laser sound for the number of seconds
1209 # given, or for 1 second (once) by default; uses my tool `sboard`
1210 laser() { sboard laser "${1:-1}" "${2:-1}"; }
1211 
1212 # get the last n lines, or 1 by default
1213 last() { tail -n "${1:-1}" "${2:--}"; }
1214 
1215 # convert a mix of pounds (LB) and weight-ounces (OZ) into kilograms
1216 lboz() {
1217     local lb="${1:-0}"
1218     lb="$(echo "${lb}" | sed 's-_--g')"
1219     local oz="${2:-0}"
1220     oz="$(echo "${oz}" | sed 's-_--g')"
1221     awk "BEGIN { print 0.45359237 * ${lb} + 0.028349523 * ${oz}; exit }"
1222 }
1223 
1224 # limit stops at the first n bytes, or 1024 bytes by default
1225 limit() { head -c "$(echo "${1:-1024}" | sed 's-_--g')" "${2:--}"; }
1226 
1227 # ensure LINES are never accidentally joined across files, by always emitting
1228 # a line-feed at the end of each line
1229 lines() {
1230     if [ -p /dev/stdout ] || [ -t 1 ]; then
1231         stdbuf -oL awk 1 "$@"
1232     else
1233         awk 1 "$@"
1234     fi
1235 }
1236 
1237 # regroup adjacent lines into n-item tab-separated lines
1238 lineup() {
1239     local command='awk'
1240     if [ -p /dev/stdout ] || [ -t 1 ]; then
1241         command='stdbuf -oL awk'
1242     fi
1243 
1244     local n="${1:-0}"
1245     [ $# -gt 0 ] && shift
1246 
1247     if [ "$n" -le 0 ]; then
1248         ${command} '
1249             NR > 1 { printf "\t" }
1250             { printf "%s", $0 }
1251             END { if (NR > 0) print "" }
1252         ' "$@"
1253         return $?
1254     fi
1255 
1256     ${command} -v n="$n" '
1257         NR % n != 1 && n > 1 { printf "\t" }
1258         { printf "%s", $0 }
1259         NR % n == 0 { print "" }
1260         END { if (NR % n != 0) print "" }
1261     ' "$@"
1262 }
1263 
1264 # LiSt MAN pages
1265 lsman() { man -k "${1:-.}"; }
1266 
1267 marklinks() {
1268     local command='sed -E'
1269     if [ -p /dev/stdout ] || [ -t 1 ]; then
1270         command='sed -E -u'
1271     fi
1272     local re='https?://[A-Za-z0-9+_.:%-]+(/[A-Za-z0-9+_.%/,#?&=-]*)*'
1273     ${command} 's-('"${re}"')-\x1b]8;;\1\x1b\\\1\x1b]8;;\x1b\\-g' "$@"
1274 }
1275 
1276 # Multi-Core MAKE runs `make` using all cores
1277 mcmake() { make -j "$(nproc)" "$@"; }
1278 
1279 # merge stderr into stdout, which is useful for piped commands
1280 merrge() { "${@:-cat /dev/null}" 2>&1; }
1281 
1282 metajq() {
1283     # https://github.com/stedolan/jq/issues/243#issuecomment-48470943
1284     jq -r -M '
1285         [
1286             path(..) |
1287             map(if type == "number" then "[]" else tostring end) |
1288             join(".") | split(".[]") | join("[]")
1289         ] | unique | map("." + .) | .[]
1290     ' "$@"
1291 }
1292 
1293 # Make In Folder
1294 mif() {
1295     local folder
1296     folder="${1:-.}"
1297     [ $# -gt 0 ] && shift
1298     env -C "${folder}" make "$@"
1299 }
1300 
1301 # MINimize DECimalS ignores all trailing decimal zeros in numbers, and even
1302 # the decimal dots themselves, when decimals in a number are all zeros
1303 # mindecs() {
1304 #     local cmd='sed -E'
1305 #     if [ -p /dev/stdout ] || [ -t 1 ]; then
1306 #         cmd='sed -E -u'
1307 #     fi
1308 #     ${cmd} 's-([0-9]+)\.0+\W-\1-g; s-([0-9]+\.[0-9]*[1-9])0+\W-\1-g' "$@"
1309 # }
1310 
1311 # Number all lines counting from 0, using a tab right after each line number
1312 n0() {
1313     if [ -p /dev/stdout ] || [ -t 1 ]; then
1314         stdbuf -oL nl -b a -w 1 -v 0 "$@"
1315     else
1316         nl -b a -w 1 -v 0 "$@"
1317     fi
1318 }
1319 
1320 # Number all lines counting from 1, using a tab right after each line number
1321 n1() {
1322     if [ -p /dev/stdout ] || [ -t 1 ]; then
1323         stdbuf -oL nl -b a -w 1 -v 1 "$@"
1324     else
1325         nl -b a -w 1 -v 1 "$@"
1326     fi
1327 }
1328 
1329 # NArrow MANual, keeps `man` narrow, even if the window/tab is wide when run
1330 naman() {
1331     local w
1332     w="$(tput cols)"
1333     w="$((w / 2 - 4))"
1334     if [ "$w" -lt 80 ]; then
1335         w=80
1336     fi
1337     MANWIDTH="$w" man "$@"
1338 }
1339 
1340 # Not AND sorts its 2 inputs, then finds lines not in common
1341 nand() {
1342     # comm -3 <(sort "$1") <(sort "$2")
1343     # dash doesn't support the process-sub syntax
1344     (sort "$1" | (sort "$2" | (comm -3 /dev/fd/3 /dev/fd/4) 4<&0) 3<&0)
1345 }
1346 
1347 # Nice DEFine dictionary-defines the words given, using an online service
1348 ndef() {
1349     local arg
1350     local gap=0
1351     local options='-MKiCRS'
1352 
1353     if [ $# -eq 0 ]; then
1354         printf "\e[38;2;204;0;0mndef: no words given\e[0m\n" >&2
1355         return 1
1356     fi
1357 
1358     if [ $# -eq 1 ]; then
1359         options='--header=1 -MKiCRS'
1360     fi
1361 
1362     for arg in "$@"; do
1363         [ "${gap}" -gt 0 ] && printf "\n"
1364         gap=1
1365         printf "\e[7m%-80s\e[0m\n" "${arg}"
1366         curl --silent "dict://dict.org/d:${arg}" | awk '
1367             { gsub(/\r$/, "") }
1368             /^151 / {
1369                 printf "\x1b[38;2;52;101;164m%s\x1b[0m\n", $0
1370                 next
1371             }
1372             /^[1-9][0-9]{2} / {
1373                 printf "\x1b[38;2;128;128;128m%s\x1b[0m\n", $0
1374                 next
1375             }
1376             1
1377         '
1378     done | less ${options}
1379 }
1380 
1381 # Nice DICTionary defines the word given locally
1382 ndict() {
1383     local arg
1384     local gap=0
1385     local options='-MKiCRS'
1386 
1387     if [ $# -eq 0 ]; then
1388         printf "\e[38;2;204;0;0mndict: no words given\e[0m\n" >&2
1389         return 1
1390     fi
1391 
1392     if [ $# -eq 1 ]; then
1393         options='--header=1 -MKiCRS'
1394     fi
1395 
1396     for arg in "$@"; do
1397         [ "${gap}" -gt 0 ] && printf "\n"
1398         gap=1
1399         printf "\e[7m%-80s\e[0m\n" "${arg}"
1400         dict "${arg}" 2>&1 | awk '
1401             NR == 1 && /^No definitions found for / { err = 1 }
1402             err { printf "\x1b[38;2;204;0;0m%s\x1b[0m\n", $0; next }
1403             1
1404         '
1405     done | less ${options}
1406 }
1407 
1408 # listen to streaming NEW WAVE music
1409 newwave() {
1410     printf "streaming \e[7mNew Wave radio\e[0m\n"
1411     mpv --quiet https://puma.streemlion.com:2910/stream
1412 }
1413 
1414 # Nice Json Query Lines colors JSONL data using the `jq` app
1415 njql() {
1416     local code="${1:-.}"
1417     [ $# -gt 0 ] && shift
1418     jq -c -C "${code} | .[]" "$@"
1419 }
1420 
1421 # play a white-noise sound lasting the number of seconds given, or for 1
1422 # second by default; uses my tool `sboard`
1423 noise() { sboard noise "${1:-1}" "${2:-1}"; }
1424 
1425 # show the current date and time
1426 now() { date +'%Y-%m-%d %H:%M:%S'; }
1427 
1428 # Nice Print Python result; uses my tool `nn`
1429 npp() {
1430     local arg
1431     for arg in "$@"; do
1432         python -c "print(${arg})"
1433     done | nn --gray
1434 }
1435 
1436 # Nice Size, using my tool `nn`
1437 ns() { wc -c "$@" | nn --gray; }
1438 
1439 # Nice TimeStamp
1440 nts() {
1441     ts '%Y-%m-%d %H:%M:%S' | sed -u \
1442         's-^-\x1b[48;2;218;218;218m\x1b[38;2;0;95;153m-; s- -\x1b[0m\t-2'
1443 }
1444 
1445 # emit nothing to output and/or discard everything from input
1446 null() { if [ $# -gt 0 ]; then "$@" > /dev/null; else cat < /dev/null; fi; }
1447 
1448 # Nice Weather Forecast gets weather forecasts, using ANSI styles and almost
1449 # filling the terminal's current width
1450 nwf() {
1451     local gap=0
1452     local width="$(($(tput cols) - 2))"
1453     local place
1454 
1455     for place in "$@"; do
1456         [ "${gap}" -gt 0 ] && printf "\n"
1457         gap=1
1458 
1459         printf "\e[7m%-${width}s\e[0m\n" "${place}"
1460 
1461         printf "%s~%s\r\n\r\n" "${place}" "${width}" |
1462         curl --silent --show-error telnet://graph.no:79 |
1463         sed -u -E \
1464             -e 's/ *\r?$//' \
1465             -e '/^\[/d' \
1466             -e 's/^ *-= *([^=]+) +=- *$/\1\n/' \
1467             -e 's/-/\x1b[38;2;196;160;0m●\x1b[0m/g' \
1468             -e 's/^( +)\x1b\[38;2;196;160;0m●\x1b\[0m/\1-/g' \
1469             -e 's/\|/\x1b[38;2;52;101;164m█\x1b[0m/g' \
1470             -e 's/#/\x1b[38;2;218;218;218m█\x1b[0m/g' \
1471             -e 's/([=\^][=\^]*)/\x1b[38;2;164;164;164m\1\x1b[0m/g' \
1472             -e 's/\*/○/g' \
1473             -e 's/_/\x1b[48;2;216;200;0m_\x1b[0m/g' \
1474             -e 's/([0-9][0-9]\/[0-9][0-9])/\x1b[7m\1\x1b[0m/g' | awk 1
1475     done | less -MKiCRS
1476 }
1477 
1478 # Print AWK expression for each input line
1479 pawk() {
1480     local command='awk'
1481     if [ -p /dev/stdout ] || [ -t 1 ]; then
1482         command='stdbuf -oL awk'
1483     fi
1484 
1485     local code="${1:-\$0}"
1486     [ $# -gt 0 ] && shift
1487 
1488     ${command} '
1489         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1490         { low = lower = tolower($0) }
1491         { print('"${code}"') }
1492     ' "$@"
1493 }
1494 
1495 # play audio/video media
1496 play() { mpv "${@:--}"; }
1497 
1498 # Print Python result
1499 pp() {
1500     local arg
1501     for arg in "$@"; do
1502         python -c "print(${arg})"
1503     done
1504 }
1505 
1506 # PRecede (input) ECHO, prepends a first line to stdin lines
1507 precho() { echo "$@" && cat /dev/stdin; }
1508 
1509 # LABEL/precede data with an ANSI-styled line
1510 prelabel() { printf "\e[7m%-*s\e[0m\n" "$(($(tput cols) - 2))" "$*"; cat -; }
1511 
1512 # PREcede (input) MEMO, prepends a first highlighted line to stdin lines
1513 prememo() { printf "\e[7m%s\e[0m\n" "$*"; cat -; }
1514 
1515 # start by joining all arguments given as a tab-separated-items line of output,
1516 # followed by all lines from stdin verbatim
1517 pretsv() {
1518     awk '
1519         BEGIN {
1520             for (i = 1; i < ARGC; i++) {
1521                 if (i > 1) printf "\t"
1522                 printf "%s", ARGV[i]
1523             }
1524             if (ARGC > 1) printf "\n"
1525             exit
1526         }
1527     ' "$@"
1528     cat -
1529 }
1530 
1531 # Quiet MPV
1532 qmpv() { mpv --quiet "${@:--}"; }
1533 
1534 # ignore stderr, without any ugly keyboard-dancing
1535 quiet() { "$@" 2> /dev/null; }
1536 
1537 # keep only lines between the 2 line numbers given, inclusively
1538 rangelines() {
1539     { [ $# -eq 2 ] || [ $# -eq 3 ]; } && [ "${1}" -le "${2}" ] && {
1540         tail -n +"${1}" "${3:--}" | head -n $(("${2}" - "${1}" + 1))
1541     }
1542 }
1543 
1544 # RANdom MANual page
1545 ranman() {
1546     find "/usr/share/man/man${1:-1}" -type f | shuf -n 1 | xargs basename |
1547         sed 's-\.gz$--' | xargs man
1548 }
1549 
1550 # play a ready-phone-line sound lasting the number of seconds given, or for 1
1551 # second by default; uses my tool `sboard`
1552 ready() { sboard ready "${1:-1}" "${2:-1}"; }
1553 
1554 # reflow/trim lines of prose (text) to improve its legibility: it's especially
1555 # useful when the text is pasted from web-pages being viewed in reader mode
1556 reprose() {
1557     local command='awk'
1558     if [ -p /dev/stdout ] || [ -t 1 ]; then
1559         command='stdbuf -oL awk'
1560     fi
1561 
1562     local w="${1:-80}"
1563     [ $# -gt 0 ] && shift
1564 
1565     ${command} '
1566         FNR == 1 && NR > 1 { print "" }
1567         { gsub(/\r$/, ""); print }
1568     ' "$@" | fold -s -w "$w" | sed -u -E 's- *\r?$--'
1569 }
1570 
1571 # REPeat STRing emits a line with a repeating string in it, given both a
1572 # string and a number in either order
1573 repstr() {
1574     awk '
1575         BEGIN {
1576             if (ARGV[2] ~ /^[+-]?[0-9]+$/) {
1577                 symbol = ARGV[1]
1578                 times = ARGV[2] + 0
1579             } else {
1580                 symbol = ARGV[2]
1581                 times = ARGV[1] + 0
1582             }
1583 
1584             if (times < 0) exit
1585             if (symbol == "") symbol = "-"
1586             s = sprintf("%*s", times, "")
1587             gsub(/ /, symbol, s)
1588             print s
1589             exit
1590         }
1591     ' "$@"
1592 }
1593 
1594 # show a RULER-like width-measuring line
1595 ruler() {
1596     [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" "" | sed -E \
1597         's- {10}-····╵····│-g; s- -·-g; s-·····-····╵-'
1598 }
1599 
1600 # Summarize via AWK calculates some numeric statistics from an AWK expression
1601 sawk() {
1602     local code="${1:-\$0}"
1603     [ $# -gt 0 ] && shift
1604 
1605     awk '
1606         BEGIN {
1607             numeric = ints = pos = zero = neg = 0
1608 
1609             inf = "+inf" + 0
1610 
1611             min = inf
1612             max = -inf
1613             sum = 0
1614             mean = 0
1615             prod = 1
1616         }
1617 
1618         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1619         { low = lower = tolower($0) }
1620 
1621         {
1622             v = ('"${code}"')
1623             if (v !~ /^ *(0|[0-9]+|[0-9]*\.[0-9]+) *$/) next
1624             v = v + 0
1625 
1626             numeric++
1627             ints += v % 1 == 0
1628             if (v > 0) pos++
1629             else if (v < 0) neg++
1630             else if (v == 0) zero++
1631 
1632             min = min < v ? min : v
1633             max = max > v ? max : v
1634             sum += v
1635             prod *= v
1636             lnSum += v <= 0 ? -inf : log(v)
1637 
1638             # advance welford`s algorithm
1639             d1 = v - mean
1640             mean += d1 / numeric
1641             d2 = v - mean
1642             meanSq += d1 * d2
1643         }
1644 
1645         END {
1646             sum = mean * numeric
1647             if (numeric == 0) lnSum = -inf
1648 
1649             # separate name-value pairs using tabs, and prepare a
1650             # pipeable command which ignores all-zero decimals
1651             OFS = "\t"
1652 
1653             print "numeric", numeric
1654             if (numeric > 0) {
1655                 print "min", sprintf("%f", min)
1656                 print "max", sprintf("%f", max)
1657                 print "sum", sprintf("%f", sum)
1658                 print "mean", sprintf("%f", mean)
1659                 print "geomean", (zero == 0 && neg == 0) ?
1660                     sprintf("%f", exp(lnSum / numeric)) :
1661                     ""
1662                 print "sd", sprintf("%f", sqrt(meanSq / numeric))
1663                 print "product", sprintf("%g", prod)
1664             } else {
1665                 print "min", ""
1666                 print "max", ""
1667                 print "sum", ""
1668                 print "mean", ""
1669                 print "geomean", ""
1670                 print "sd", ""
1671                 print "product", ""
1672             }
1673             print "integer", ints
1674             print "positive", pos
1675             print "zero", zero
1676             print "negative", neg
1677         }
1678     ' "$@" | sed -E 's-([0-9]+)\.0+$-\1-g; s-([0-9]+\.[0-9]*[1-9])0+$-\1-g'
1679 }
1680 
1681 # SystemCTL; `sysctl` is already taken for a separate/unrelated app
1682 sctl() { systemctl "$@" 2>&1 | less -MKiCRS; }
1683 
1684 # show a unique-looking SEParator line; useful to run between commands
1685 # which output walls of text
1686 sep() {
1687     [ "${1:-80}" -gt 0 ] &&
1688         printf "\e[48;2;218;218;218m%${1:-80}s\e[0m\n" "" | sed 's- -·-g'
1689 }
1690 
1691 # webSERVE files in a folder as localhost, using the port number given, or
1692 # port 8080 by default
1693 serve() {
1694     printf "\e[7mserving files in %s\e[0m\n" "${2:-$(pwd)}" >&2
1695     python3 -m http.server "${1:-8080}" -d "${2:-.}"
1696 }
1697 
1698 # SET DIFFerence sorts its 2 inputs, then finds lines not in the 2nd input
1699 setdiff() {
1700     # comm -23 <(sort "$1") <(sort "$2")
1701     # dash doesn't support the process-sub syntax
1702     (sort "$1" | (sort "$2" | (comm -23 /dev/fd/3 /dev/fd/4) 4<&0) 3<&0)
1703 }
1704 
1705 # SET INtersection, sorts its 2 inputs, then finds common lines
1706 setin() {
1707     # comm -12 <(sort "$1") <(sort "$2")
1708     # dash doesn't support the process-sub syntax
1709     (sort "$1" | (sort "$2" | (comm -12 /dev/fd/3 /dev/fd/4) 4<&0) 3<&0)
1710 }
1711 
1712 # SET SUBtraction sorts its 2 inputs, then finds lines not in the 2nd input
1713 setsub() {
1714     # comm -23 <(sort "$1") <(sort "$2")
1715     # dash doesn't support the process-sub syntax
1716     (sort "$1" | (sort "$2" | (comm -23 /dev/fd/3 /dev/fd/4) 4<&0) 3<&0)
1717 }
1718 
1719 # Show Files (and folders), coloring folders and links
1720 sf() {
1721     local arg
1722     local gap=0
1723     local options='-MKiCRS'
1724 
1725     if [ $# -le 1 ]; then
1726         options='--header=1 -MKiCRS'
1727     fi
1728 
1729     for arg in "${@:-.}"; do
1730         [ "${gap}" -gt 0 ] && printf "\n"
1731         printf "\e[7m%s\e[0m\n\n" "$(realpath "${arg}")"
1732         gap=1
1733 
1734         ls -al --file-type --color=never --time-style iso "${arg}" | awk '
1735             BEGIN {
1736                 drep = "\x1b[38;2;0;135;255m\x1b[48;2;228;228;228m&\x1b[0m"
1737                 lrep = "\x1b[38;2;0;135;95m\x1b[48;2;228;228;228m&\x1b[0m"
1738             }
1739 
1740             NR < 4 { next }
1741             (NR - 3) % 5 == 1 && (NR - 3) > 1 { print "" }
1742 
1743             {
1744                 gsub(/^(d[rwx-]+)/, drep)
1745                 gsub(/^(l[rwx-]+)/, lrep)
1746                 printf "%6d  %s\n", NR - 3, $0; fflush()
1747             }
1748         '
1749     done | less ${options}
1750 }
1751 
1752 # run apps in color-mode, using the popular option `--color=always`
1753 shine() {
1754     local cmd="$1"
1755     [ $# -gt 0 ] && shift
1756     "${cmd}" --color=always "$@"
1757 }
1758 
1759 # skip the first n lines, or the 1st line by default
1760 skip() { tail -n +$(("${1:-1}" + 1)) "${2:--}"; }
1761 
1762 # skip the last n lines, or the last line by default
1763 skiplast() { head -n -"${1:-1}" "${2:--}"; }
1764 
1765 # SLOW/delay lines from the standard-input, waiting the number of seconds
1766 # given for each line, or waiting 1 second by default
1767 slow() {
1768     local seconds="${1:-1}"
1769     (
1770         IFS="$(printf "\n")"
1771         while read -r line; do
1772             sleep "${seconds}"
1773             printf "%s\n" "${line}"
1774         done
1775     )
1776 }
1777 
1778 # Show Latest Podcasts, using my tools `podfeed` and `si`
1779 slp() {
1780     local title
1781     title="Latest Podcast Episodes as of $(date +'%F %T')"
1782     podfeed -title "${title}" "$@" | si
1783 }
1784 
1785 # emit the first line as is, sorting all lines after that, using the
1786 # `sort` command, passing all/any arguments/options to it
1787 sortrest() {
1788     awk -v sort="sort $*" '
1789         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
1790         { gsub(/\r$/, "") }
1791         NR == 1 { print; fflush() }
1792         NR >= 2 { print | sort }
1793     '
1794 }
1795 
1796 # SORt Tab-Separated Values: emit the first line as is, sorting all lines after
1797 # that, using the `sort` command in TSV (tab-separated values) mode, passing
1798 # all/any arguments/options to it
1799 sortsv() {
1800     awk -v sort="sort -t \"$(printf '\t')\" $*" '
1801         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
1802         { gsub(/\r$/, "") }
1803         NR == 1 { print; fflush() }
1804         NR >= 2 { print | sort }
1805     '
1806 }
1807 
1808 # emit a line with the number of spaces given in it
1809 spaces() { [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" ""; }
1810 
1811 # SQUeeze horizontal spaces and STOMP vertical gaps
1812 squomp() {
1813     local command='awk'
1814     if [ -p /dev/stdout ] || [ -t 1 ]; then
1815         command='stdbuf -oL awk'
1816     fi
1817 
1818     ${command} '
1819         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
1820         /^\r?$/ { empty = 1; next }
1821         empty { if (n > 0) print ""; empty = 0 }
1822 
1823         {
1824             gsub(/^ +| *\r?$/, "")
1825             gsub(/ *\t */, "\t")
1826             gsub(/  +/, " ")
1827             print; n++
1828         }
1829     ' "$@"
1830 }
1831 
1832 # STOMP vertical gaps, turning runs of empty lines into single empty lines
1833 stomp() {
1834     local command='awk'
1835     if [ -p /dev/stdout ] || [ -t 1 ]; then
1836         command='stdbuf -oL awk'
1837     fi
1838 
1839     ${command} '
1840         /^\r?$/ { empty = 1; next }
1841         empty { if (n > 0) print ""; empty = 0 }
1842         { print; n++ }
1843     ' "$@"
1844 }
1845 
1846 substr() {
1847     local command='awk'
1848     if [ -p /dev/stdout ] || [ -t 1 ]; then
1849         command='stdbuf -oL awk'
1850     fi
1851     if [ $# -lt 2 ]; then
1852         printf "missing 1-based start index, and substring length\n" >&2
1853         exit 1
1854     fi
1855 
1856     ${command} '{ print substr($0, '"$1"', '"$2"') }'
1857 }
1858 
1859 # add a final sums row after all input lines
1860 sums() {
1861     local command='awk'
1862     if [ -p /dev/stdout ] || [ -t 1 ]; then
1863         command='stdbuf -oL awk'
1864     fi
1865 
1866     ${command} '
1867         { gsub(/\r$/, "") }
1868 
1869         NR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1870 
1871         {
1872             if (n < NF) n = NF
1873             for (i = 1; i <= NF; i++) sums[i] += $i
1874             print
1875         }
1876 
1877         END {
1878             for (i = 1; i <= n; i++) {
1879                 if (i > 1) printf(FS)
1880                 printf("%s", sums[i])
1881             }
1882             if (n > 0) printf "\n"
1883         }
1884     ' "$@"
1885 }
1886 
1887 # TAC Lines outputs input-lines in reverse order, last one first, and so on...
1888 tacl() {
1889     awk '
1890         { gsub(/\r$/, ""); lines[NR] = $0 }
1891         END { for (i = NR; i >= 1; i--) print lines[i] }
1892     ' "$@"
1893 }
1894 
1895 # show a reverse-sorted tally of all lines read, where ties are sorted
1896 # alphabetically
1897 # tally() {
1898 #     awk -v sortcmd="sort -t \"$(printf '\t')\" -rnk2 -k1d" '
1899 #         # reassure users by instantly showing the header
1900 #         BEGIN { print "value\ttally"; fflush() }
1901 #         { gsub(/\r$/, ""); t[$0]++ }
1902 #         END { for (k in t) { printf("%s\t%d\n", k, t[k]) | sortcmd } }
1903 #     ' "$@"
1904 # }
1905 
1906 # Tally (lines) with AWK
1907 tawk() {
1908     local code="${1:-\$0}"
1909     [ $# -gt 0 ] && shift
1910 
1911     awk -v sortcmd="sort -t '\t' -rnk1" '
1912         function maybe(x, y) {
1913             if (y == "") { y = x; x = $0 }
1914             return match(x, y) ? substr(x, RSTART, RLENGTH) : ""
1915         }
1916 
1917         BEGIN { print "tally\tvalue"; fflush() }
1918 
1919         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1920         { low = lower = tolower($0) }
1921 
1922         {
1923             v = ('"${code}"')
1924             if (!tally[v]++) ordkeys[++oklen] = v
1925         }
1926 
1927         END {
1928             for (i = 1; i <= oklen; i++) {
1929                 k = ordkeys[i]
1930                 printf "%d\t%s\n", tally[k], k | sortcmd
1931             }
1932         }
1933     ' "$@"
1934 }
1935 
1936 # Simulate the cadence of old-fashioned TELETYPE machines
1937 teletype() {
1938     awk '
1939         {
1940             gsub(/\r$/, "")
1941 
1942             n = length($0)
1943             for (i = 1; i <= n; i++) {
1944                 if (code = system("sleep 0.015")) exit code
1945                 printf "%s", substr($0, i, 1); fflush()
1946             }
1947 
1948             if (code = system("sleep 0.75")) exit code
1949             printf "\n"; fflush()
1950         }
1951 
1952         # END { if (NR > 0 && code != 0) printf "\n" }
1953     ' "$@"
1954 }
1955 
1956 # show current date in a specifc format
1957 today() { date +'%Y-%m-%d %a %b %d'; }
1958 
1959 # get the first n lines, or 1 by default
1960 toline() { head -n "${1:-1}" "${2:--}"; }
1961 
1962 # lowercase all ASCII symbols
1963 tolower() {
1964     if [ -p /dev/stdout ] || [ -t 1 ]; then
1965         stdbuf -oL awk '{ print tolower($0) }' "$@"
1966     else
1967         awk '{ print tolower($0) }' "$@"
1968     fi
1969 }
1970 
1971 # play a tone/sine-wave sound lasting the number of seconds given, or for 1
1972 # second by default: after the optional duration, the next optional arguments
1973 # are the volume and the tone-frequency; uses my tools `sboard` and `waveout`
1974 tone() {
1975     if [ "${3:-440}" -eq 440 ]; then
1976         sboard tone "${1:-1}" "${2:-1}"
1977     else
1978         waveout "${1:-1}" "${2:-1} * sin(${3:-440} * tau * t)" |
1979             mpv --really-quiet -
1980     fi
1981 }
1982 
1983 # get the processes currently using the most cpu
1984 topcpu() {
1985     local n="${1:-10}"
1986     [ "$n" -gt 0 ] && ps aux | awk '
1987         NR == 1 { print; fflush() }
1988         NR > 1 { print | "sort -rnk3" }
1989     ' | head -n "$(("$n" + 1))"
1990 }
1991 
1992 # get the processes currently using the most memory
1993 topmemory() {
1994     local n="${1:-10}"
1995     [ "$n" -gt 0 ] && ps aux | awk '
1996         NR == 1 { print; fflush() }
1997         NR > 1 { print | "sort -rnk6" }
1998     ' | head -n "$(("$n" + 1))"
1999 }
2000 
2001 # transpose (switch) rows and columns from tables
2002 transpose() {
2003     awk '
2004         { gsub(/\r$/, "") }
2005 
2006         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
2007 
2008         {
2009             for (i = 1; i <= NF; i++) lines[i][NR] = $i
2010             if (maxitems < NF) maxitems = NF
2011         }
2012 
2013         END {
2014             for (j = 1; j <= maxitems; j++) {
2015                 for (i = 1; i <= NR; i++) {
2016                     if (i > 1) printf "\t"
2017                     printf "%s", lines[j][i]
2018                 }
2019                 printf "\n"
2020             }
2021         }
2022     ' "$@"
2023 }
2024 
2025 # Unique via AWK, avoids lines duplicating the expression given
2026 uawk() {
2027     local code="${1:-\$0}"
2028     [ $# -gt 0 ] && shift
2029 
2030     local command='awk'
2031     if [ -p /dev/stdout ] || [ -t 1 ]; then
2032         command='stdbuf -oL awk'
2033     fi
2034 
2035     ${command} '
2036         function maybe(x, y) {
2037             if (y == "") { y = x; x = $0 }
2038             return match(x, y) ? substr(x, RSTART, RLENGTH) : ""
2039         }
2040 
2041         BEGIN { for (i = 1; i < ARGC; i++) if (f[ARGV[i]]++) delete ARGV[i] }
2042         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
2043         { low = lower = tolower($0) }
2044         !c['"${code}"']++
2045     ' "$@"
2046 }
2047 
2048 # Underline Every 5 lines: make groups of 5 lines stand out by underlining
2049 # the last line of each such group
2050 ue5() {
2051     local command='awk'
2052     if [ -p /dev/stdout ] || [ -t 1 ]; then
2053         command='stdbuf -oL awk'
2054     fi
2055 
2056     ${command} '
2057         NR % 5 == 0 && NR != 1 {
2058             gsub(/\x1b\[0m/, "\x1b[0m\x1b[4m")
2059             printf("\x1b[4m%s\x1b[0m\n", $0)
2060             next
2061         }
2062         1
2063     ' "$@"
2064 }
2065 
2066 # only keep UNIQUE lines, keeping them in their original order
2067 unique() {
2068     local command='awk'
2069     if [ -p /dev/stdout ] || [ -t 1 ]; then
2070         command='stdbuf -oL awk'
2071     fi
2072 
2073     ${command} '
2074         BEGIN { for (i = 1; i < ARGC; i++) if (f[ARGV[i]]++) delete ARGV[i] }
2075         !c[$0]++
2076     ' "$@"
2077 }
2078 
2079 # fix lines, ignoring leading UTF-8_BOMs (byte-order-marks) on each input's
2080 # first line, turning all end-of-line CRLF byte-pairs into single line-feeds,
2081 # and ensuring each input's last line ends with a line-feed; trailing spaces
2082 # are also ignored
2083 unixify() {
2084     local command='awk'
2085     if [ -p /dev/stdout ] || [ -t 1 ]; then
2086         command='stdbuf -oL awk'
2087     fi
2088 
2089     ${command} '
2090         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
2091         { gsub(/ *\r?$/, ""); print }
2092     ' "$@"
2093 }
2094 
2095 # skip the first/leading n bytes
2096 unleaded() { tail -c +$(("$1" + 1)) "${2:--}"; }
2097 
2098 # go UP n folders, or go up 1 folder by default
2099 up() {
2100     if [ "${1:-1}" -le 0 ]; then
2101         cd .
2102     else
2103         cd "$(printf "%${1:-1}s" "" | sed 's- -../-g')" || return $?
2104     fi
2105 }
2106 
2107 # convert United States Dollars into CAnadian Dollars, using the latest
2108 # official exchange rates from the bank of canada; during weekends, the
2109 # latest rate may be from a few days ago; the default amount of usd to
2110 # convert is 1, when not given
2111 usd2cad() {
2112     local site='https://www.bankofcanada.ca/valet/observations/group'
2113     local csv_rates="${site}/FX_RATES_DAILY/csv"
2114     local url="${csv_rates}?start_date=$(date -d '3 days ago' +'%Y-%m-%d')"
2115     curl -s "${url}" | awk -F, -v amount="$(echo "${1:-1}" | sed 's-_--g')" '
2116         /USD/ { for (i = 1; i <= NF; i++) if($i ~ /USD/) j = i }
2117         END { gsub(/"/, "", $j); if (j != 0) printf "%.2f\n", amount * $j }
2118     '
2119 }
2120 
2121 # View Nice Table / Very Nice Table; uses my tool `ncol`
2122 vnt() {
2123     nl -b a -w 1 -v 0 "$@" | ncol | awk '(NR - 1) % 5 == 1 { print "" } 1' |
2124         less -MKiCRS --header=1
2125 }
2126 
2127 # View Text, turning documents into plain-text if needed; uses `pandoc`
2128 vt() {
2129     local arg
2130     local gap=0
2131     local options='-MKiCRS'
2132 
2133     if [ $# -eq 1 ]; then
2134         options='--header=1 -MKiCRS'
2135     fi
2136 
2137     if [ $# -eq 0 ]; then
2138         pandoc -s -t plain - 2>&1 | less -MKiCRS
2139     else
2140         for arg in "$@"; do
2141             [ "${gap}" -eq 1 ] && printf "\n"
2142             gap=1
2143             printf "\e[7m%-80s\e[0m\n" "${arg}"
2144             pandoc -s -t plain "${arg}" 2>&1 | awk 1
2145         done | less ${options}
2146     fi
2147 }
2148 
2149 # What Are These (?) shows what the names given to it are/do
2150 wat() {
2151     local arg
2152     local gap=0
2153 
2154     if [ $# -eq 0 ]; then
2155         echo "$0"
2156         return 0
2157     fi
2158 
2159     for arg in "$@"; do
2160         [ "${gap}" -gt 0 ] && printf "\n"
2161         gap=1
2162         printf "\e[7m%-80s\e[0m\n" "${arg}"
2163 
2164         while alias "${arg}" > /dev/null 2> /dev/null; do
2165             arg="$(alias "${arg}" | sed -E "s-^[^=]+=['\"](.+)['\"]\$-\\1-")"
2166         done
2167 
2168         if echo "${arg}" | grep -q ' '; then
2169             printf "%s\n" "${arg}"
2170             continue
2171         fi
2172 
2173         if declare -f "${arg}"; then
2174             continue
2175         fi
2176 
2177         if which "${arg}" > /dev/null 2> /dev/null; then
2178             which "${arg}"
2179             continue
2180         fi
2181 
2182         printf "\e[38;2;204;0;0m%s not found\e[0m\n" "${arg}"
2183     done | less -MKiCRS
2184 }
2185 
2186 # find all WEB/hyperLINKS (https:// and http://) in the input text
2187 weblinks() {
2188     local arg
2189     local re='https?://[A-Za-z0-9+_.:%-]+(/[A-Za-z0-9+_.%/,#?&=-]*)*'
2190     for arg in "${@:--}"; do
2191         grep --line-buffered -E -o "${re}" "${arg}"
2192     done
2193 }
2194 
2195 # recursively find all files with trailing spaces/CRs
2196 whichtrails() { rg -c --line-buffered '[ \r]+$' "${@:-.}"; }
2197 
2198 # XARGS Lines, runs `xargs` using whole lines as extra arguments
2199 xargsl() {
2200     if [ -p /dev/stdout ] || [ -t 1 ]; then
2201         stdbuf -oL awk -v ORS='\000' '
2202             FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
2203             { gsub(/\r$/, ""); print }
2204         ' | stdbuf -oL xargs -0 "$@"
2205     else
2206         awk -v ORS='\000' '
2207             FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
2208             { gsub(/\r$/, ""); print }
2209         ' | xargs -0 "$@"
2210     fi
2211 }
2212 
2213 # Youtube Audio Player
2214 yap() {
2215     # some youtube URIs end with extra playlist/tracker parameters
2216     local url="$(echo "$1" | sed 's-&.*--')"
2217     mpv "$(yt-dlp -x --audio-format best --get-url "${url}" 2> /dev/null)"
2218 }
2219 
2220 # show a calendar for the current YEAR, or for the year given
2221 year() {
2222     {
2223         # show the current date/time center-aligned
2224         printf \
2225             "%21s\e[38;2;78;154;6m%s\e[0m  \e[38;2;52;101;164m%s\e[0m\n\n" \
2226             "" "$(date +'%a %b %d %Y')" "$(date +'%H:%M')"
2227         # debian linux has a different `cal` app which highlights the day
2228         if [ -e "/usr/bin/ncal" ]; then
2229             # fix debian/ncal's weird way to highlight the current day
2230             ncal -C -y "$@" | sed -E 's/_\x08(.)/\x1b[7m\1\x1b[0m/g'
2231         else
2232             cal -y "$@"
2233         fi
2234     } | less -MKiCRS
2235 }
2236 
2237 # show the current date in the YYYY-MM-DD format
2238 ymd() { date +'%Y-%m-%d'; }