File: dedent.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 # dedent [options...] [files...] 27 # 28 # Ignore the common leading-space indentation from the input(s). 29 # 30 # The help option is `-h`, `--h`, `-help`, or `--help`. 31 32 33 buffered=0 34 35 case "$1" in 36 -b|--b|-buffered|--buffered) 37 buffered=1 38 shift 39 ;; 40 41 -h|--h|-help|--help) 42 awk '/^# +dedent /, /^$/ { gsub(/^# ?/, ""); print }' "$0" 43 exit 0 44 ;; 45 esac 46 47 [ "$1" = '--' ] && shift 48 49 # show all non-existing files given 50 failed=0 51 for arg in "$@"; do 52 if [ "${arg}" = "-" ]; then 53 continue 54 fi 55 if [ ! -e "${arg}" ]; then 56 printf "no file named \"%s\"\n" "${arg}" >&2 57 failed=1 58 fi 59 done 60 61 if [ "${failed}" -gt 0 ]; then 62 exit 2 63 fi 64 65 flush=0 66 if [ "${buffered}" -eq 0 ] && { [ -p /dev/stdout ] || [ -t 1 ]; }; then 67 flush=1 68 fi 69 70 awk -v flush="${flush}" ' 71 BEGIN { n = -1 } 72 73 { 74 if (n == 0) { 75 print 76 if (flush) fflush() 77 next 78 } 79 80 indent = 0 81 if (match($0, /^ +/)) indent = RLENGTH 82 83 m = n 84 if (n > indent || n < 0) n = indent 85 if (m != 0 && n == 0) { 86 for (i = 1; i <= NR; i++) print lines[i] 87 for (i = 1; i <= NR; i++) delete lines[i] 88 next 89 } 90 91 lines[NR] = $0 92 } 93 94 END { 95 if (n > 0) for (i = 1; i <= NR; i++) print substr(lines[i], n + 1) 96 } 97 ' "$@"