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

Re: Array parameter expansion: take n-th word from array elements



25.06.2017, 15:46, "Alexander Groß" <agross@xxxxxxxxxxxxxxxx>:
> Hi all,
>
> I would like to parse some output from a command that generates an array of
> the following elements:
>
> Main System.Xml.XPath - 4.3
> Main System.Xml.XPath.XDocument - 4.3
> Test Castle.Core - 4.0
> Test FsCheck - 2.9
>
> E.g.
>
> foo=('a interesting - b' 'a also-interesting - c')
>
> I would like to take the second word from each and every of the array
> elements (interesting also-interesting). Unfortunately,
>
> print -l ${foo[2]}
>
> prints the second element, 'a also-interesting - c'.
>
> A for loop works:
>
> local -a filtered
> for package in $foo; do
>   # Split by space and take second word.
>   filtered+="${${(s. .)package}[2]}"
> done
>
> But I wonder if there is a better way using parameter expansion. Here's
> what I came up with so far:
> print -l ${${(s. .)foo}[2]}
>
> Unfortunately, it just prints 'interesting'.
>
> Any ideas pointing me in the right direction are greatly appreciated!

I would just go with ${#} and ${%}:

    % foo=('a interesting - b' 'a also-interesting - c')
    % echo ${${foo% - *}#* }
    interesting also-interesting

>
> Alex
> --
> Alexander Groß
> http://therightstuff.de/



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