Created
June 25, 2022 19:24
-
-
Save eggplants/b1beceabe3b848e30d90cefa20a9f8e8 to your computer and use it in GitHub Desktop.
De-indent in Bash like Python's textwrap.dedent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
function dedent() { | |
local src min | |
src="$(expand -t 2 -)" # 1 tab = 2 spaces | |
if [ -z "$src" ]; then | |
echo "dedent: input is empty." >&2 | |
return 1 | |
fi | |
min="$( | |
echo "$src" | | |
sed -r 's/^( *).*$/\1/' | | |
awk 'BEGIN{m=-log(0)}{m=(a=length)<m ? a : m}END{print m}' | |
)" | |
if [[ "$min" = "-inf" ]]; then | |
echo "dedent: failed to calc min length of \`/^ */'." >&2 | |
return 1 | |
fi | |
echo "$src" | sed -r 's/^ {'"$min"'}//' | |
} | |
function main() { | |
dedent <<'A' | |
test1 | |
test2 | |
test3 | |
test4 | |
A | |
} | |
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then | |
main "$@" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment