Skip to content

Instantly share code, notes, and snippets.

@eggplants
Created June 25, 2022 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eggplants/b1beceabe3b848e30d90cefa20a9f8e8 to your computer and use it in GitHub Desktop.
Save eggplants/b1beceabe3b848e30d90cefa20a9f8e8 to your computer and use it in GitHub Desktop.
De-indent in Bash like Python's textwrap.dedent
#!/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