Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: array element subsetting
- X-seq: zsh-users 14971
- From: Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx>
- To: "S. Cowles" <scowles@xxxxxxxx>, zsh-users@xxxxxxx
- Subject: Re: array element subsetting
- Date: Fri, 26 Mar 2010 07:41:48 -0700
- In-reply-to: <alpine.LN8.2.00.1003260202111.10812@xxxxxxxxxxxxxxx>
- List-help: <mailto:zsh-users-help@zsh.org>
- List-id: Zsh Users List <zsh-users.zsh.org>
- List-post: <mailto:zsh-users@zsh.org>
- Mailing-list: contact zsh-users-help@xxxxxxx; run by ezmlm
- References: <Xns9D456D0F33B88zzappergmailcom@xxxxxxxxxxxx> <20100324120359.GA29984@xxxxxxxxxxxxxxxxxxxxxxxxxx> <Xns9D45D21E0B19Azzappergmailcom@xxxxxxxxxxxx> <alpine.LN8.2.00.1003260202111.10812@xxxxxxxxxxxxxxx>
On Mar 26, 2:24am, S. Cowles wrote:
}
} 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"
} )
(1) can be done with the (M) parameter flag and simple head/tail:
print ${(M)a#?}
To generalize to the Nth element, ${(M)${(M)a#?(#c$N)}%?} (requires
extendedglob, of course).
(2) is more difficult to do without looping, because zsh doesn't
support multidimensional arrays, so you have to force an eval step
via the (e) flag:
print ${(e):-'${${=:-'${^a}'}[2]}'}
However, this yields the second character of arrays that contain
only one word, because ${=...} reduces singular arrays to scalars.
A simple workaround is to insert an empty dummy element at the tail:
print ${(e):-'${${=:-'${^a}' ""}[2]}'}
In the event there are special characters in the strings in $a, an
extra level of quoting can be added and then removed:
print ${(e):-'${${=${(Q):-'${(q)^a}' ""}}[2]}'}
However, this removes again the empty element inserted by the double
quotes, i.e., it returns nothing for the short array rather than an
empty second element (use "print -l" in those examples to see the
difference more clearly). Remove the (e) if you want to see what's
going on with the ${(q)^a} business.
Messages sorted by:
Reverse Date,
Date,
Thread,
Author