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

Re: substring extraction



On Mon, May 08, 2006 at 09:32:50AM +0200, Com MN PG P E B Consultant 3 wrote:
> bash has the nice feature to extract a substring from a shell variable.
> For example
> 
>    # bash example
>    var=abcd
>    echo ${var:1:2} # Start at offset 1, returns 2 characters
> 
> displays 
> 
>    bc

That's a ksh feature borrowed by bash. And as of many ksh
features, it's got its flaws. That one conflicts with the
${var:-default-value} Bourne operator, so that you need to do
${var: -1} (add a space) to get the last char.

> Is there an easy way to achieve a similar effect in zsh, without
> reverting to external
> tools such as awk or sed?
[...]

In zsh:

$var[2,3]

zsh can do it because arrays and scalar variables are two
different types. In zsh, $var[2,5] gives the 2nd to 5th element
when $var is of array type, and 2nd to 5th char when $var is
scalar. In ksh/bash all variables are arrays and $var is a
shortcut for ${var[0]} (though it's not completely true of
bash).

-- 
Stéphane



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