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

array element subsetting




I am trying to figure out the correct syntax for constructing two one-liner subsetting operations on arrays. I have two objectives: 1) select nth character from each array element, and 2) select nth element within each array element.

The array these methods operate upon is something simple such as:
a=(
    "satu two trio"
    "sah funf seis"
    "boundarycase"
    "revert to pattern"
)

For the first case, the solution I came up with is:

print -l ${a//#%(#b)(?)*/${match[1]}}

for the first character of each element, or

print -l ${a//#%(#b)?(#c2)(?(#c1))*/${match[1]}}

for 3rd character of each element (generalizable to [n,m] elements).

For the second case, doing word splitting on each array element, I came up with two variations to print out the second word in each element.

print -l ${a//#%(#b)*[[:IFS:]]##(*)[[:IFS:]]##*/${match[1]}}

print -l ${a//#%(#b)[[:WORD:]]##[^[:WORD:]]##([[:WORD:]]##)[^[:WORD:]]##*/${match[1]}}

(Though not important for my uses, these both fail with the boundary case where the array element contains only one word.)

Isn't there a better/cleaner way to accomplish this, especially for the second objective?

Thanks.



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