Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Feature request: ${(l[-3][0])var} to do left padding *without truncation*



On Sat, Aug 3, 2024 at 4:23 PM Stephane Chazelas <stephane@xxxxxxxxxxxx> wrote:
>
> At the moment:
>
> $ set -o extendedglob
> $ a=1-12-123-1234-12345
> $ echo ${a//(#m)<->/${(l[3][0])MATCH}}
> 001-012-123-234-345
>
> Numbers are "l"eft padded to a length of 3 with 0s, but also
> truncated to 3 digits when longer. It's often not desired.
>
> Same happens with -3 (though that doesn't seem to be documented):
>
> $ echo ${a//(#m)<->/${(l[-3][0])MATCH}}
> 001-012-123-234-345
>
> One can avoid the truncation with things like:
>
> $ echo ${a//(#m)<->/${(l[$#MATCH > 3 ? $#match : 3][0])MATCH}}
> 001-012-123-1234-12345
>
> Including wia a math function helper:
>
> $ atleast() (( $#MATCH > $1 ? $#MATCH : $1 )); functions -M atleast
> $ echo ${a//(#m)<->/${(l[atleast(3)][0])MATCH}}
> 001-012-123-1234-12345
>
> But that's a bit cumbersome and needs to be adapted when the "m"
> flag is also used..
>
> Would it be possible to have a way to disable the truncating,
> maybe via negative numbers where ${(l[3][0])var} would
> pad-and-truncate as is currently does, but ${(l[-3][0])var}
> would pad only (leave longer strings alone)?
>
> Same for "r"ight-padding.
>
> Or is there already a smarter way to do it than with my ternary
> arithmetic expression above?

(No actual answer to the question follows)

I was trying to be clever, but ran into the same issue here as well,
% typeset -Z3 MATCH
% echo ${a//(#m)<->/$MATCH}
001-012-123-234-345

This kinda works but gives you an extra - at the end,
% printf '%03i-' ${(s:-:)a}
001-012-123-1234-12345-
% printf -v a '%03i-' ${(s:-:)a}; echo ${a%-}
001-012-123-1234-12345

-- 
Mikael Magnusson




Messages sorted by: Reverse Date, Date, Thread, Author