On Tuesday 29 November 2011 21:57:42 David C. Rankin wrote:
I want a function 'ellipse' that will take a string 'str' and trim it to length 'len' and set the 'end' number (default = 3) of characters to 'chr' (default='.'). So if I call it like this:
myvar=0123456789
echo "mydefvar: $(ellipse $myvar 7)" echo "mynewvar: $(ellipse $myvar 7 3 '*')"
I get:
mydefvar: 0123... mynewvar: 0123***
What I have come up with is the following, but I would like comment on how to make it better, etc.. Is there a way to eliminate the for loop and just use string substitution to overwrite the last 'end' number of characters with 'chr' that would be more efficient? What says the brain trust.
ellipse() {
# validate sufficient parameters passed [[ -z $1 ]] || [[ -z $2 ]] && { echo "ERROR: Insufficient input in fxn ellipse"; return 1; }
str="$1" lim="$2" end=${3:-3} chr=${4:-.}
# validate integers [ $lim -eq $lim ] 2>/dev/null || return 1 [ $end -eq $end ] 2>/dev/null || return 1
[[ ${#str} -gt $lim ]] && newstr=${str:0:$((lim-end))} { for((i=$((lim-end));i<$lim;i++)); do newstr=${newstr}${chr} done
echo "$newstr" } || { echo "$str" } }
If you're still inclined to go the bash way, perhaps something like this would work (parameter validation and other sanity checks omitted): function ellipse() { str="${1}" lim="${2}" rem=${3:-3} char=${4:-.} [[ ${#str} -gt ${lim} ]] && { begin=${str:0:$((lim-rem))}; end=${str:$((lim-rem)):${rem}}; echo ${begin}${end//?/${char}}; } || echo "${str}" } -- Martti -- To unsubscribe, e-mail: opensuse+unsubscribe@opensuse.org To contact the owner, e-mail: opensuse+owner@opensuse.org