Skip to content

Instantly share code, notes, and snippets.

@dinhoabreu
Created December 31, 2015 22:44
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 dinhoabreu/7b048be0379683cd30ee to your computer and use it in GitHub Desktop.
Save dinhoabreu/7b048be0379683cd30ee to your computer and use it in GitHub Desktop.
Bash - Stream line padding
#!/usr/bin/env bash
function str_pad() {
local pad_length="$1" pad_string="$2" pad_type="$3"
local pad length llength offset rlength
pad="$(eval "printf '%0.${#pad_string}s' '${pad_string}'{1..$pad_length}")"
pad="${pad:0:$pad_length}"
if [[ "$pad_type" == "left" ]]; then
while read line; do
line="${line:0:$pad_length}"
length="$(( pad_length - ${#line} ))"
echo "${pad:0:$length}$line"
done
elif [[ "$pad_type" == "both" ]]; then
while read line; do
line="${line:0:$pad_length}"
length="$(( pad_length - ${#line} ))"
llength="$(( length / 2 ))"
offset="$(( llength + ${#line} ))"
rlength="$(( llength + (length % 2) ))"
echo "${pad:0:$llength}$line${pad:$offset:$rlength}"
done
else
while read line; do
line="${line:0:$pad_length}"
length="$(( pad_length - ${#line} ))"
echo "$line${pad:${#line}:$length}"
done
fi
}
# Usage:
# str_pad 50 '-' right <<<'Hello world!'
# str_pad 50 '-' left <<<'Hello world!'
# str_pad 50 '-' both <<<'Hello world!'
[[ $_ == $0 ]] && str_pad "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment