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                 printf("\x1b[38;2;204;0;0m%s\x1b[0m\n", 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                 printf("\x1b[38;2;204;0;0m%s\x1b[0m\n", 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 Systemctl Status
1440 nss() {
1441     if [ $# -eq 0 ]; then
1442         # avoid having/showing other commands running, when they're not needed
1443         local res
1444         res="$(systemctl status "$@" 2>&1)"
1445         echo "${res}" | less -MKiCRS
1446         return $?
1447     fi
1448 
1449     systemctl status "$@" 2>&1 | sed -E \
1450         -e 's-\x1b\[[^A-Za-z][A-Za-z]--g' \
1451         -e 's-(^[^ ] )([^ ]+\.service)-\1\x1b[7m\2\x1b[0m-' \
1452         -e 's- (enabled)- \x1b[38;2;0;135;95m\x1b[7m\1\x1b[0m-g' \
1453         -e 's- (disabled)- \x1b[38;2;215;95;0m\x1b[7m\1\x1b[0m-g' \
1454         -e 's- (active \(running\))- \x1b[38;2;0;135;95m\x1b[7m\1\x1b[0m-g' \
1455         -e 's- (inactive \(dead\))- \x1b[38;2;204;0;0m\x1b[7m\1\x1b[0m-g' \
1456         -e 's-^(Unit .* could not .*)$-\x1b[38;2;204;0;0m\x1b[7m\1\x1b[0m\n-' \
1457         -e 's-(\[WARN\].*)$-\x1b[38;2;215;95;0m\x1b[7m\1\x1b[0m\n-' \
1458         -e 's-(\[ERR\].*)$-\x1b[38;2;204;0;0m\x1b[7m\1\x1b[0m\n-' |
1459     if [ "${COLORBLIND}" = 1 ] || [ "${COLOR_BLIND}" = 1 ]; then
1460         # color-blind-friendly version using blue instead of green
1461         sed 's-\x1b\[38;2;0;135;95m-\x1b[38;2;0;95;215m-g'
1462     else
1463         # leave green colors untouched
1464         cat
1465     fi | less -MKiCRS
1466 }
1467 
1468 # Nice TimeStamp
1469 nts() {
1470     ts '%Y-%m-%d %H:%M:%S' | sed -u \
1471         's-^-\x1b[48;2;218;218;218m\x1b[38;2;0;95;153m-; s- -\x1b[0m\t-2'
1472 }
1473 
1474 # emit nothing to output and/or discard everything from input
1475 null() { if [ $# -gt 0 ]; then "$@" > /dev/null; else cat < /dev/null; fi; }
1476 
1477 # Nice Weather Forecast gets weather forecasts, using ANSI styles and almost
1478 # filling the terminal's current width
1479 nwf() {
1480     local gap=0
1481     local width="$(($(tput cols) - 2))"
1482     local place
1483 
1484     for place in "$@"; do
1485         [ "${gap}" -gt 0 ] && printf "\n"
1486         gap=1
1487 
1488         printf "\e[7m%-${width}s\e[0m\n" "${place}"
1489 
1490         printf "%s~%s\r\n\r\n" "${place}" "${width}" |
1491         curl --silent --show-error telnet://graph.no:79 |
1492         sed -u -E \
1493             -e 's/ *\r?$//' \
1494             -e '/^\[/d' \
1495             -e 's/^ *-= *([^=]+) +=- *$/\1\n/' \
1496             -e 's/-/\x1b[38;2;196;160;0m●\x1b[0m/g' \
1497             -e 's/^( +)\x1b\[38;2;196;160;0m●\x1b\[0m/\1-/g' \
1498             -e 's/\|/\x1b[38;2;52;101;164m█\x1b[0m/g' \
1499             -e 's/#/\x1b[38;2;218;218;218m█\x1b[0m/g' \
1500             -e 's/([=\^][=\^]*)/\x1b[38;2;164;164;164m\1\x1b[0m/g' \
1501             -e 's/\*/○/g' \
1502             -e 's/_/\x1b[48;2;216;200;0m_\x1b[0m/g' \
1503             -e 's/([0-9][0-9]\/[0-9][0-9])/\x1b[7m\1\x1b[0m/g' | awk 1
1504     done | less -MKiCRS
1505 }
1506 
1507 # Print AWK expression for each input line
1508 pawk() {
1509     local command='awk'
1510     if [ -p /dev/stdout ] || [ -t 1 ]; then
1511         command='stdbuf -oL awk'
1512     fi
1513 
1514     local code="${1:-\$0}"
1515     [ $# -gt 0 ] && shift
1516 
1517     ${command} '
1518         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1519         { low = lower = tolower($0) }
1520         { print('"${code}"') }
1521     ' "$@"
1522 }
1523 
1524 # play audio/video media
1525 play() { mpv "${@:--}"; }
1526 
1527 # Print Python result
1528 pp() {
1529     local arg
1530     for arg in "$@"; do
1531         python -c "print(${arg})"
1532     done
1533 }
1534 
1535 # PRecede (input) ECHO, prepends a first line to stdin lines
1536 precho() { echo "$@" && cat /dev/stdin; }
1537 
1538 # LABEL/precede data with an ANSI-styled line
1539 prelabel() { printf "\e[7m%-*s\e[0m\n" "$(($(tput cols) - 2))" "$*"; cat -; }
1540 
1541 # PREcede (input) MEMO, prepends a first highlighted line to stdin lines
1542 prememo() { printf "\e[7m%s\e[0m\n" "$*"; cat -; }
1543 
1544 # start by joining all arguments given as a tab-separated-items line of output,
1545 # followed by all lines from stdin verbatim
1546 pretsv() {
1547     awk '
1548         BEGIN {
1549             for (i = 1; i < ARGC; i++) {
1550                 if (i > 1) printf "\t"
1551                 printf "%s", ARGV[i]
1552             }
1553             if (ARGC > 1) printf "\n"
1554             exit
1555         }
1556     ' "$@"
1557     cat -
1558 }
1559 
1560 # Quiet MPV
1561 qmpv() { mpv --quiet "${@:--}"; }
1562 
1563 # ignore stderr, without any ugly keyboard-dancing
1564 quiet() { "$@" 2> /dev/null; }
1565 
1566 # keep only lines between the 2 line numbers given, inclusively
1567 rangelines() {
1568     { [ $# -eq 2 ] || [ $# -eq 3 ]; } && [ "${1}" -le "${2}" ] && {
1569         tail -n +"${1}" "${3:--}" | head -n $(("${2}" - "${1}" + 1))
1570     }
1571 }
1572 
1573 # RANdom MANual page
1574 ranman() {
1575     find "/usr/share/man/man${1:-1}" -type f | shuf -n 1 | xargs basename |
1576         sed 's-\.gz$--' | xargs man
1577 }
1578 
1579 # play a ready-phone-line sound lasting the number of seconds given, or for 1
1580 # second by default; uses my tool `sboard`
1581 ready() { sboard ready "${1:-1}" "${2:-1}"; }
1582 
1583 # reflow/trim lines of prose (text) to improve its legibility: it's especially
1584 # useful when the text is pasted from web-pages being viewed in reader mode
1585 reprose() {
1586     local command='awk'
1587     if [ -p /dev/stdout ] || [ -t 1 ]; then
1588         command='stdbuf -oL awk'
1589     fi
1590 
1591     local w="${1:-80}"
1592     [ $# -gt 0 ] && shift
1593 
1594     ${command} '
1595         FNR == 1 && NR > 1 { print "" }
1596         { gsub(/\r$/, ""); print }
1597     ' "$@" | fold -s -w "$w" | sed -u -E 's- *\r?$--'
1598 }
1599 
1600 # REPeat STRing emits a line with a repeating string in it, given both a
1601 # string and a number in either order
1602 repstr() {
1603     awk '
1604         BEGIN {
1605             if (ARGV[2] ~ /^[+-]?[0-9]+$/) {
1606                 symbol = ARGV[1]
1607                 times = ARGV[2] + 0
1608             } else {
1609                 symbol = ARGV[2]
1610                 times = ARGV[1] + 0
1611             }
1612 
1613             if (times < 0) exit
1614             if (symbol == "") symbol = "-"
1615             s = sprintf("%*s", times, "")
1616             gsub(/ /, symbol, s)
1617             print s
1618             exit
1619         }
1620     ' "$@"
1621 }
1622 
1623 # show a RULER-like width-measuring line
1624 ruler() {
1625     [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" "" | sed -E \
1626         's- {10}-····╵····│-g; s- -·-g; s-·····-····╵-'
1627 }
1628 
1629 # Summarize via AWK calculates some numeric statistics from an AWK expression
1630 sawk() {
1631     local code="${1:-\$0}"
1632     [ $# -gt 0 ] && shift
1633 
1634     awk '
1635         BEGIN {
1636             numeric = ints = pos = zero = neg = 0
1637 
1638             inf = "+inf" + 0
1639 
1640             min = inf
1641             max = -inf
1642             sum = 0
1643             mean = 0
1644             prod = 1
1645         }
1646 
1647         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1648         { low = lower = tolower($0) }
1649 
1650         {
1651             v = ('"${code}"')
1652             if (v !~ /^ *(0|[0-9]+|[0-9]*\.[0-9]+) *$/) next
1653             v = v + 0
1654 
1655             numeric++
1656             ints += v % 1 == 0
1657             if (v > 0) pos++
1658             else if (v < 0) neg++
1659             else if (v == 0) zero++
1660 
1661             min = min < v ? min : v
1662             max = max > v ? max : v
1663             sum += v
1664             prod *= v
1665             lnSum += v <= 0 ? -inf : log(v)
1666 
1667             # advance welford`s algorithm
1668             d1 = v - mean
1669             mean += d1 / numeric
1670             d2 = v - mean
1671             meanSq += d1 * d2
1672         }
1673 
1674         END {
1675             sum = mean * numeric
1676             if (numeric == 0) lnSum = -inf
1677 
1678             # separate name-value pairs using tabs, and prepare a
1679             # pipeable command which ignores all-zero decimals
1680             OFS = "\t"
1681 
1682             print "numeric", numeric
1683             if (numeric > 0) {
1684                 print "min", sprintf("%f", min)
1685                 print "max", sprintf("%f", max)
1686                 print "sum", sprintf("%f", sum)
1687                 print "mean", sprintf("%f", mean)
1688                 print "geomean", (zero == 0 && neg == 0) ?
1689                     sprintf("%f", exp(lnSum / numeric)) :
1690                     ""
1691                 print "sd", sprintf("%f", sqrt(meanSq / numeric))
1692                 print "product", sprintf("%g", prod)
1693             } else {
1694                 print "min", ""
1695                 print "max", ""
1696                 print "sum", ""
1697                 print "mean", ""
1698                 print "geomean", ""
1699                 print "sd", ""
1700                 print "product", ""
1701             }
1702             print "integer", ints
1703             print "positive", pos
1704             print "zero", zero
1705             print "negative", neg
1706         }
1707     ' "$@" | sed -E 's-([0-9]+)\.0+$-\1-g; s-([0-9]+\.[0-9]*[1-9])0+$-\1-g'
1708 }
1709 
1710 # SystemCTL; `sysctl` is already taken for a separate/unrelated app
1711 sctl() { systemctl "$@" 2>&1 | less -MKiCRS; }
1712 
1713 # show a unique-looking SEParator line; useful to run between commands
1714 # which output walls of text
1715 sep() {
1716     [ "${1:-80}" -gt 0 ] &&
1717         printf "\e[48;2;218;218;218m%${1:-80}s\e[0m\n" "" | sed 's- -·-g'
1718 }
1719 
1720 # webSERVE files in a folder as localhost, using the port number given, or
1721 # port 8080 by default
1722 serve() {
1723     printf "\e[7mserving files in %s\e[0m\n" "${2:-$(pwd)}" >&2
1724     python3 -m http.server "${1:-8080}" -d "${2:-.}"
1725 }
1726 
1727 # SET DIFFerence sorts its 2 inputs, then finds lines not in the 2nd input
1728 setdiff() {
1729     # comm -23 <(sort "$1") <(sort "$2")
1730     # dash doesn't support the process-sub syntax
1731     (sort "$1" | (sort "$2" | (comm -23 /dev/fd/3 /dev/fd/4) 4<&0) 3<&0)
1732 }
1733 
1734 # SET INtersection, sorts its 2 inputs, then finds common lines
1735 setin() {
1736     # comm -12 <(sort "$1") <(sort "$2")
1737     # dash doesn't support the process-sub syntax
1738     (sort "$1" | (sort "$2" | (comm -12 /dev/fd/3 /dev/fd/4) 4<&0) 3<&0)
1739 }
1740 
1741 # SET SUBtraction sorts its 2 inputs, then finds lines not in the 2nd input
1742 setsub() {
1743     # comm -23 <(sort "$1") <(sort "$2")
1744     # dash doesn't support the process-sub syntax
1745     (sort "$1" | (sort "$2" | (comm -23 /dev/fd/3 /dev/fd/4) 4<&0) 3<&0)
1746 }
1747 
1748 # Show Files (and folders), coloring folders and links
1749 sf() {
1750     local arg
1751     local gap=0
1752     local options='-MKiCRS'
1753 
1754     if [ $# -le 1 ]; then
1755         options='--header=1 -MKiCRS'
1756     fi
1757 
1758     for arg in "${@:-.}"; do
1759         [ "${gap}" -gt 0 ] && printf "\n"
1760         printf "\e[7m%s\e[0m\n\n" "$(realpath "${arg}")"
1761         gap=1
1762 
1763         ls -al --file-type --color=never --time-style iso "${arg}" | awk '
1764             BEGIN {
1765                 drep = "\x1b[38;2;0;135;255m\x1b[48;2;228;228;228m&\x1b[0m"
1766                 lrep = "\x1b[38;2;0;135;95m\x1b[48;2;228;228;228m&\x1b[0m"
1767             }
1768 
1769             NR < 4 { next }
1770             (NR - 3) % 5 == 1 && (NR - 3) > 1 { print "" }
1771 
1772             {
1773                 gsub(/^(d[rwx-]+)/, drep)
1774                 gsub(/^(l[rwx-]+)/, lrep)
1775                 printf "%6d  %s\n", NR - 3, $0; fflush()
1776             }
1777         '
1778     done | less "${options}"
1779 }
1780 
1781 # run apps in color-mode, using the popular option `--color=always`
1782 shine() {
1783     local cmd="$1"
1784     [ $# -gt 0 ] && shift
1785     "${cmd}" --color=always "$@"
1786 }
1787 
1788 # skip the first n lines, or the 1st line by default
1789 skip() { tail -n +$(("${1:-1}" + 1)) "${2:--}"; }
1790 
1791 # skip the last n lines, or the last line by default
1792 skiplast() { head -n -"${1:-1}" "${2:--}"; }
1793 
1794 # SLOW/delay lines from the standard-input, waiting the number of seconds
1795 # given for each line, or waiting 1 second by default
1796 slow() {
1797     local seconds="${1:-1}"
1798     (
1799         IFS="$(printf "\n")"
1800         while read -r line; do
1801             sleep "${seconds}"
1802             printf "%s\n" "${line}"
1803         done
1804     )
1805 }
1806 
1807 # Show Latest Podcasts, using my tools `podfeed` and `si`
1808 slp() {
1809     local title
1810     title="Latest Podcast Episodes as of $(date +'%F %T')"
1811     podfeed -title "${title}" "$@" | si
1812 }
1813 
1814 # emit the first line as is, sorting all lines after that, using the
1815 # `sort` command, passing all/any arguments/options to it
1816 sortrest() {
1817     awk -v sort="sort $*" '
1818         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
1819         { gsub(/\r$/, "") }
1820         NR == 1 { print; fflush() }
1821         NR >= 2 { print | sort }
1822     '
1823 }
1824 
1825 # SORt Tab-Separated Values: emit the first line as is, sorting all lines after
1826 # that, using the `sort` command in TSV (tab-separated values) mode, passing
1827 # all/any arguments/options to it
1828 sortsv() {
1829     awk -v sort="sort -t \"$(printf '\t')\" $*" '
1830         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
1831         { gsub(/\r$/, "") }
1832         NR == 1 { print; fflush() }
1833         NR >= 2 { print | sort }
1834     '
1835 }
1836 
1837 # emit a line with the number of spaces given in it
1838 spaces() { [ "${1:-80}" -gt 0 ] && printf "%${1:-80}s\n" ""; }
1839 
1840 # SQUeeze horizontal spaces and STOMP vertical gaps
1841 squomp() {
1842     local command='awk'
1843     if [ -p /dev/stdout ] || [ -t 1 ]; then
1844         command='stdbuf -oL awk'
1845     fi
1846 
1847     ${command} '
1848         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
1849         /^\r?$/ { empty = 1; next }
1850         empty { if (n > 0) print ""; empty = 0 }
1851 
1852         {
1853             gsub(/^ +| *\r?$/, "")
1854             gsub(/ *\t */, "\t")
1855             gsub(/  +/, " ")
1856             print; n++
1857         }
1858     ' "$@"
1859 }
1860 
1861 # STOMP vertical gaps, turning runs of empty lines into single empty lines
1862 stomp() {
1863     local command='awk'
1864     if [ -p /dev/stdout ] || [ -t 1 ]; then
1865         command='stdbuf -oL awk'
1866     fi
1867 
1868     ${command} '
1869         /^\r?$/ { empty = 1; next }
1870         empty { if (n > 0) print ""; empty = 0 }
1871         { print; n++ }
1872     ' "$@"
1873 }
1874 
1875 substr() {
1876     local command='awk'
1877     if [ -p /dev/stdout ] || [ -t 1 ]; then
1878         command='stdbuf -oL awk'
1879     fi
1880     if [ $# -lt 2 ]; then
1881         printf "missing 1-based start index, and substring length\n" >&2
1882         exit 1
1883     fi
1884 
1885     ${command} '{ print substr($0, '"$1"', '"$2"') }'
1886 }
1887 
1888 # add a final sums row after all input lines
1889 sums() {
1890     local command='awk'
1891     if [ -p /dev/stdout ] || [ -t 1 ]; then
1892         command='stdbuf -oL awk'
1893     fi
1894 
1895     ${command} '
1896         { gsub(/\r$/, "") }
1897 
1898         NR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1899 
1900         {
1901             if (n < NF) n = NF
1902             for (i = 1; i <= NF; i++) sums[i] += $i
1903             print
1904         }
1905 
1906         END {
1907             for (i = 1; i <= n; i++) {
1908                 if (i > 1) printf(FS)
1909                 printf("%s", sums[i])
1910             }
1911             if (n > 0) printf "\n"
1912         }
1913     ' "$@"
1914 }
1915 
1916 # TAC Lines outputs input-lines in reverse order, last one first, and so on...
1917 tacl() {
1918     awk '
1919         { gsub(/\r$/, ""); lines[NR] = $0 }
1920         END { for (i = NR; i >= 1; i--) print lines[i] }
1921     ' "$@"
1922 }
1923 
1924 # show a reverse-sorted tally of all lines read, where ties are sorted
1925 # alphabetically
1926 # tally() {
1927 #     awk -v sortcmd="sort -t \"$(printf '\t')\" -rnk2 -k1d" '
1928 #         # reassure users by instantly showing the header
1929 #         BEGIN { print "value\ttally"; fflush() }
1930 #         { gsub(/\r$/, ""); t[$0]++ }
1931 #         END { for (k in t) { printf("%s\t%d\n", k, t[k]) | sortcmd } }
1932 #     ' "$@"
1933 # }
1934 
1935 # Tally (lines) with AWK
1936 tawk() {
1937     local code="${1:-\$0}"
1938     [ $# -gt 0 ] && shift
1939 
1940     awk -v sortcmd="sort -t '\t' -rnk1" '
1941         function maybe(x, y) {
1942             if (y == "") { y = x; x = $0 }
1943             return match(x, y) ? substr(x, RSTART, RLENGTH) : ""
1944         }
1945 
1946         BEGIN { print "tally\tvalue"; fflush() }
1947 
1948         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
1949         { low = lower = tolower($0) }
1950 
1951         {
1952             v = ('"${code}"')
1953             if (!tally[v]++) ordkeys[++oklen] = v
1954         }
1955 
1956         END {
1957             for (i = 1; i <= oklen; i++) {
1958                 k = ordkeys[i]
1959                 printf "%d\t%s\n", tally[k], k | sortcmd
1960             }
1961         }
1962     ' "$@"
1963 }
1964 
1965 # Simulate the cadence of old-fashioned TELETYPE machines
1966 teletype() {
1967     awk '
1968         {
1969             gsub(/\r$/, "")
1970 
1971             n = length($0)
1972             for (i = 1; i <= n; i++) {
1973                 if (code = system("sleep 0.015")) exit code
1974                 printf "%s", substr($0, i, 1); fflush()
1975             }
1976 
1977             if (code = system("sleep 0.75")) exit code
1978             printf "\n"; fflush()
1979         }
1980 
1981         # END { if (NR > 0 && code != 0) printf "\n" }
1982     ' "$@"
1983 }
1984 
1985 # show current date in a specifc format
1986 today() { date +'%Y-%m-%d %a %b %d'; }
1987 
1988 # get the first n lines, or 1 by default
1989 toline() { head -n "${1:-1}" "${2:--}"; }
1990 
1991 # lowercase all ASCII symbols
1992 tolower() {
1993     if [ -p /dev/stdout ] || [ -t 1 ]; then
1994         stdbuf -oL awk '{ print tolower($0) }' "$@"
1995     else
1996         awk '{ print tolower($0) }' "$@"
1997     fi
1998 }
1999 
2000 # play a tone/sine-wave sound lasting the number of seconds given, or for 1
2001 # second by default: after the optional duration, the next optional arguments
2002 # are the volume and the tone-frequency; uses my tools `sboard` and `waveout`
2003 tone() {
2004     if [ "${3:-440}" -eq 440 ]; then
2005         sboard tone "${1:-1}" "${2:-1}"
2006     else
2007         waveout "${1:-1}" "${2:-1} * sin(${3:-440} * tau * t)" |
2008             mpv --really-quiet -
2009     fi
2010 }
2011 
2012 # get the processes currently using the most cpu
2013 topcpu() {
2014     local n="${1:-10}"
2015     [ "$n" -gt 0 ] && ps aux | awk '
2016         NR == 1 { print; fflush() }
2017         NR > 1 { print | "sort -rnk3" }
2018     ' | head -n "$(("$n" + 1))"
2019 }
2020 
2021 # get the processes currently using the most memory
2022 topmemory() {
2023     local n="${1:-10}"
2024     [ "$n" -gt 0 ] && ps aux | awk '
2025         NR == 1 { print; fflush() }
2026         NR > 1 { print | "sort -rnk6" }
2027     ' | head -n "$(("$n" + 1))"
2028 }
2029 
2030 # transpose (switch) rows and columns from tables
2031 transpose() {
2032     awk '
2033         { gsub(/\r$/, "") }
2034 
2035         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
2036 
2037         {
2038             for (i = 1; i <= NF; i++) lines[i][NR] = $i
2039             if (maxitems < NF) maxitems = NF
2040         }
2041 
2042         END {
2043             for (j = 1; j <= maxitems; j++) {
2044                 for (i = 1; i <= NR; i++) {
2045                     if (i > 1) printf "\t"
2046                     printf "%s", lines[j][i]
2047                 }
2048                 printf "\n"
2049             }
2050         }
2051     ' "$@"
2052 }
2053 
2054 # Unique via AWK, avoids lines duplicating the expression given
2055 uawk() {
2056     local code="${1:-\$0}"
2057     [ $# -gt 0 ] && shift
2058 
2059     local command='awk'
2060     if [ -p /dev/stdout ] || [ -t 1 ]; then
2061         command='stdbuf -oL awk'
2062     fi
2063 
2064     ${command} '
2065         function maybe(x, y) {
2066             if (y == "") { y = x; x = $0 }
2067             return match(x, y) ? substr(x, RSTART, RLENGTH) : ""
2068         }
2069 
2070         BEGIN { for (i = 1; i < ARGC; i++) if (f[ARGV[i]]++) delete ARGV[i] }
2071         FNR == 1 { FS = /\t/ ? "\t" : " "; $0 = $0 }
2072         { low = lower = tolower($0) }
2073         !c['"${code}"']++
2074     ' "$@"
2075 }
2076 
2077 # Underline Every 5 lines: make groups of 5 lines stand out by underlining
2078 # the last line of each such group
2079 ue5() {
2080     local command='awk'
2081     if [ -p /dev/stdout ] || [ -t 1 ]; then
2082         command='stdbuf -oL awk'
2083     fi
2084 
2085     ${command} '
2086         NR % 5 == 0 && NR != 1 {
2087             gsub(/\x1b\[0m/, "\x1b[0m\x1b[4m")
2088             printf("\x1b[4m%s\x1b[0m\n", $0)
2089             next
2090         }
2091         1
2092     ' "$@"
2093 }
2094 
2095 # only keep UNIQUE lines, keeping them in their original order
2096 unique() {
2097     local command='awk'
2098     if [ -p /dev/stdout ] || [ -t 1 ]; then
2099         command='stdbuf -oL awk'
2100     fi
2101 
2102     ${command} '
2103         BEGIN { for (i = 1; i < ARGC; i++) if (f[ARGV[i]]++) delete ARGV[i] }
2104         !c[$0]++
2105     ' "$@"
2106 }
2107 
2108 # fix lines, ignoring leading UTF-8_BOMs (byte-order-marks) on each input's
2109 # first line, turning all end-of-line CRLF byte-pairs into single line-feeds,
2110 # and ensuring each input's last line ends with a line-feed; trailing spaces
2111 # are also ignored
2112 unixify() {
2113     local command='awk'
2114     if [ -p /dev/stdout ] || [ -t 1 ]; then
2115         command='stdbuf -oL awk'
2116     fi
2117 
2118     ${command} '
2119         FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
2120         { gsub(/ *\r?$/, ""); print }
2121     ' "$@"
2122 }
2123 
2124 # skip the first/leading n bytes
2125 unleaded() { tail -c +$(("$1" + 1)) "${2:--}"; }
2126 
2127 # go UP n folders, or go up 1 folder by default
2128 up() {
2129     if [ "${1:-1}" -le 0 ]; then
2130         cd .
2131     else
2132         cd "$(printf "%${1:-1}s" "" | sed 's- -../-g')" || return $?
2133     fi
2134 }
2135 
2136 # convert United States Dollars into CAnadian Dollars, using the latest
2137 # official exchange rates from the bank of canada; during weekends, the
2138 # latest rate may be from a few days ago; the default amount of usd to
2139 # convert is 1, when not given
2140 usd2cad() {
2141     local site='https://www.bankofcanada.ca/valet/observations/group'
2142     local csv_rates="${site}/FX_RATES_DAILY/csv"
2143     local url="${csv_rates}?start_date=$(date -d '3 days ago' +'%Y-%m-%d')"
2144     curl -s "${url}" | awk -F, -v amount="$(echo "${1:-1}" | sed 's-_--g')" '
2145         /USD/ { for (i = 1; i <= NF; i++) if($i ~ /USD/) j = i }
2146         END { gsub(/"/, "", $j); if (j != 0) printf "%.2f\n", amount * $j }
2147     '
2148 }
2149 
2150 # View Nice Table / Very Nice Table; uses my tool `ncol`
2151 vnt() {
2152     nl -b a -w 1 -v 0 "$@" | ncol | awk '(NR - 1) % 5 == 1 { print "" } 1' |
2153         less -MKiCRS --header=1
2154 }
2155 
2156 # View Text, turning documents into plain-text if needed; uses `pandoc`
2157 vt() {
2158     local arg
2159     local gap=0
2160     local options='-MKiCRS'
2161 
2162     if [ $# -eq 1 ]; then
2163         options='--header=1 -MKiCRS'
2164     fi
2165 
2166     if [ $# -eq 0 ]; then
2167         pandoc -s -t plain - 2>&1 | less -MKiCRS
2168     else
2169         for arg in "$@"; do
2170             [ "${gap}" -eq 1 ] && printf "\n"
2171             gap=1
2172             printf "\e[7m%-80s\e[0m\n" "${arg}"
2173             pandoc -s -t plain "${arg}" 2>&1 | awk 1
2174         done | less "${options}"
2175     fi
2176 }
2177 
2178 # What Are These (?) shows what the names given to it are/do
2179 wat() {
2180     local arg
2181     local gap=0
2182 
2183     if [ $# -eq 0 ]; then
2184         echo "$0"
2185         return 0
2186     fi
2187 
2188     for arg in "$@"; do
2189         [ "${gap}" -gt 0 ] && printf "\n"
2190         gap=1
2191         printf "\e[7m%-80s\e[0m\n" "${arg}"
2192 
2193         while alias "${arg}" > /dev/null 2> /dev/null; do
2194             arg="$(alias "${arg}" | sed -E "s-^[^=]+=['\"](.+)['\"]\$-\\1-")"
2195         done
2196 
2197         if echo "${arg}" | grep -q ' '; then
2198             printf "%s\n" "${arg}"
2199             continue
2200         fi
2201 
2202         if declare -f "${arg}"; then
2203             continue
2204         fi
2205 
2206         if which "${arg}" > /dev/null 2> /dev/null; then
2207             which "${arg}"
2208             continue
2209         fi
2210 
2211         printf "\e[38;2;204;0;0m%s not found\e[0m\n" "${arg}"
2212     done | less -MKiCRS
2213 }
2214 
2215 # find all WEB/hyperLINKS (https:// and http://) in the input text
2216 weblinks() {
2217     local arg
2218     local re='https?://[A-Za-z0-9+_.:%-]+(/[A-Za-z0-9+_.%/,#?&=-]*)*'
2219     for arg in "${@:--}"; do
2220         grep --line-buffered -E -o "${re}" "${arg}"
2221     done
2222 }
2223 
2224 # recursively find all files with trailing spaces/CRs
2225 whichtrails() { rg -c --line-buffered '[ \r]+$' "${@:-.}"; }
2226 
2227 # XARGS Lines, runs `xargs` using whole lines as extra arguments
2228 xargsl() {
2229     if [ -p /dev/stdout ] || [ -t 1 ]; then
2230         stdbuf -oL awk -v ORS='\000' '
2231             FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
2232             { gsub(/\r$/, ""); print }
2233         ' | stdbuf -oL xargs -0 "$@"
2234     else
2235         awk -v ORS='\000' '
2236             FNR == 1 { gsub(/^\xef\xbb\xbf/, "") }
2237             { gsub(/\r$/, ""); print }
2238         ' | xargs -0 "$@"
2239     fi
2240 }
2241 
2242 # Youtube Audio Player
2243 yap() {
2244     # some youtube URIs end with extra playlist/tracker parameters
2245     local url="$(echo "$1" | sed 's-&.*--')"
2246     mpv "$(yt-dlp -x --audio-format best --get-url "${url}" 2> /dev/null)"
2247 }
2248 
2249 # show a calendar for the current YEAR, or for the year given
2250 year() {
2251     {
2252         # show the current date/time center-aligned
2253         printf \
2254             "%21s\e[38;2;78;154;6m%s\e[0m  \e[38;2;52;101;164m%s\e[0m\n\n" \
2255             "" "$(date +'%a %b %d %Y')" "$(date +'%H:%M')"
2256         # debian linux has a different `cal` app which highlights the day
2257         if [ -e "/usr/bin/ncal" ]; then
2258             # fix debian/ncal's weird way to highlight the current day
2259             ncal -C -y "$@" | sed -E 's/_\x08(.)/\x1b[7m\1\x1b[0m/g'
2260         else
2261             cal -y "$@"
2262         fi
2263     } | less -MKiCRS
2264 }
2265 
2266 # show the current date in the YYYY-MM-DD format
2267 ymd() { date +'%Y-%m-%d'; }