File: wcl.sh
   1 #!/bin/sh
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright (c) 2026 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 # wcl [options...] [files...]
  27 #
  28 # WC Lines runs `wc -cl --total=never` with the files given, turning its
  29 # output into lines of tab-separated values: this removes output-parsing
  30 # ambiguities, in case of filepaths with spaces in them.
  31 #
  32 # The options are, available both in single and double-dash versions
  33 #
  34 #   -h, -help              show this help message
  35 #   -s, -sort              backward-sort by size/byte-count
  36 #   -s=WHAT, -sort=WHAT    backward-sort using the field given (`c`, `l`)
  37 
  38 
  39 sorting='cat -'
  40 
  41 case "$1" in
  42     -h|--h|-help|--help)
  43         awk '/^# +wcl /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  44         exit 0
  45     ;;
  46 
  47     -s|--s|-sort|--sort|\
  48     -s=b|--s=b|-sort=b|--sort=b|\
  49     -s=bytes|--s=bytes|-sort=bytes|--sort=bytes|\
  50     -s=c|--s=c|-sort=c|--sort=c|\
  51     -s=s|--s=s|-sort=s|--sort=s|\
  52     -s=size|--s=size|-sort=size|--sort=size)
  53         sorting='sort -k1,1rn'; shift
  54     ;;
  55 
  56     -s=l|--s=l|-sort=l|--sort=l|\
  57     -s=lines|--s=lines|-sort=lines|--sort=lines)
  58         sorting='sort -k2,2rn'; shift
  59     ;;
  60 
  61     -*)
  62         printf "%s: unsupported option %s\n" "$0" "$1" >&2
  63         exit 1
  64     ;;
  65 esac
  66 
  67 printf "file\tlines\tbytes\n"
  68 
  69 wc -cl --total=never "$@" \
  70 | sed -E 's-^ +--; s- +-\t-1; s- +-\t-1' \
  71 | ${sorting} \
  72 | awk -F "\t" -v OFS="\t" '{ print $3, $1, $2 }'