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

A challenge – non-extendedglob whitespace trimming



Hello!
I think this is a valid challenge:

1. One can do the following to strip whitespace from string $str:

    str=${${str##[[:space:]]##}%%[[:space:]]##}

This uses ## operator and thus requires setopt extendedglob.

2. Extendedglob-free code that does the same:

        str="${str#"${str%%[! $'\t']*}"}" # leading whitespace
        str="${str%"${str##*[! $'\t']}"}" # trailing whitespace

It's tricky, but the main thing one has to notice to grasp this: The
inner ${str%%...} substitution will match from end to beginning of
string till last non-whitespace. So it will left only leading
whitespace. Which is then removed from start of the string with
#-subst.

3. I have an array `pairs', holding elements like this: pairs=( "a ->
b" "  c ->d    " ), etc. I want to obtain array with additional split
on "->" (so it is nicely fitting into a hash, key-a val-b, etc.).
Following is an extendedglob-dependant code that performs the split
and also trims leading and trailing whitespace from all elements:

    pairs=( "${(@)${(@)${(@s:->:)pairs}##[[:space:]]##}%%[[:space:]]##}" )

4. Is there a extendedglob-free (not depending on it) version of the
above point 3.?

--
Sebastian Gniazdowski
News: https://twitter.com/ZdharmaI
IRC: https://kiwiirc.com/client/chat.freenode.net:+6697/#zplugin
Blog: http://zdharma.org



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