
Hello, On Tue, 29 Nov 2011, 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.
I can't think of a way, but that's probably because I've "perl" in the back of my head.
ellipse() {
# validate sufficient parameters passed [[ -z $1 ]] || [[ -z $2 ]] && { echo "ERROR: Insufficient input in fxn ellipse"; return 1; }
You need to quote $1 and $2 here. Try with empty $1 or $2 to see why.
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" } }
JFTR: if test ${#str} -gt $lim; then newstr=${str:0:$((lim-end))}; perl -e "printf qq[%s%${end}s\n], qq[$newstr], qq[$chr] x $end;" else printf "$str\n"; fi Of course you could truncate $str in perl to etc. pp, but once using perl you should probably do the whole script (or at least the function) in perl, otherwise it'll be much slower. HTH, -dnh -- Who do I have to kill to get some attention around here! -- Georgia 'George' Lass, Dead Like Me -- To unsubscribe, e-mail: opensuse+unsubscribe@opensuse.org To contact the owner, e-mail: opensuse+owner@opensuse.org