#!/bin/sh # The MIT License (MIT) # # Copyright © 2024 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # wctabs [options...] [filepaths...] # # Run `wc` (word-count) with the arguments given, turning its output into # lines of tab-separated values: this removes output-parsing ambiguities, # in case of filepaths with spaces in them. # # You can run `wc --help` to see all its options, which you can also use # with this script. # handle help option(s) case "$1" in -h|--h|-help|--help) awk '/^# +wctabs/, /^$/ { gsub(/^# ?/, ""); print }' "$0" exit 0 ;; esac # avoid testing all permutations of up to 5 single-char options stats=$(awk 'BEGIN { bytes = 0 chars = 0 words = 0 lines = 0 maxll = 0 for (i = 1; i < ARGC; i++) { s = ARGV[i] delete ARGV[i] if (s !~ /^-/) continue switch (s) { case "--bytes": bytes = 1 break case "--chars": chars = 1 break case "--lines": lines = 1 break case "--words": words = 1 break case "--max-line-length": maxll = 1 break default: if (s ~ /c/) bytes = 1 else if (s ~ /m/) chars = 1 else if (s ~ /w/) words = 1 else if (s ~ /l/) lines = 1 else if (s ~ /L/) maxll = 1 else { stderr = "/dev/stderr" printf "\x1b[31munsupported wc option %s\x1b[0m\n", s > stderr } break } } stats = bytes + chars + words + lines + maxll # `wc` defaults to 3 stats when not explicitly given any option print (stats == 0) ? 3 : stats }' "$@") errmsg="only up to 5 wc options are supported" longcmd="s-^ +--; s- +-\t-1; s- +-\t-1; s- +-\t-1; s- +-\t-1; s- +-\t-1" case "${stats}" in 1) wc "$@" | sed -E 's-^ +--; s- +-\t-1';; 2) wc "$@" | sed -E 's-^ +--; s- +-\t-1; s- +-\t-1';; 3) wc "$@" | sed -E 's-^ +--; s- +-\t-1; s- +-\t-1; s- +-\t-1';; 4) wc "$@" | sed -E 's-^ +--; s- +-\t-1; s- +-\t-1; s- +-\t-1; s- +-\t-1';; 5) wc "$@" | sed -E "${longcmd}";; *) printf "\e[31m%s: %s\e[0m\n" "$0" "${errmsg}" > /dev/stderr exit 1 ;; esac