Created
December 31, 2015 22:44
-
-
Save dinhoabreu/7b048be0379683cd30ee to your computer and use it in GitHub Desktop.
Bash - Stream line padding
This file contains 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 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