Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: Negative length parameter expansion
- X-seq: zsh-users 20142
- From: ZyX <kp-pav@xxxxxxxxx>
- To: Thorsten Kampe <thorsten@xxxxxxxxxxxxxxxx>, "zsh-users@xxxxxxx" <zsh-users@xxxxxxx>
- Subject: Re: Negative length parameter expansion
- Date: Sun, 12 Apr 2015 14:54:12 +0300
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=yandex.ru; s=mail; t=1428839653; bh=rvaM8ImFMnfgEj+qufFmeNIQat6IRvUWYi1XWv0PDQw=; h=From:To:In-Reply-To:References:Subject:Date; b=b5E7CZrnLnW7FUTLkOTA3QGVEKWmhAW9MeTWM3sJqYpiRPcF2aFghTxeUnbVGjX2O cTcooZWk4F+2V05hEuaUpU0S0c3FPkqV6JtXwrXs1s5G7Ayw/Pzy/HZToIpjeHKyBF srHTzT3fluc7T27eb+gZKKevH6Qf1ldNQbNNT7ic=
- In-reply-to: <mgdlp5$dap$1@ger.gmane.org>
- 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: <mgd6pj$ioh$1@ger.gmane.org> <2421271428831232@web29o.yandex.ru> <mgdlp5$dap$1@ger.gmane.org>
12.04.2015, 14:45, "Thorsten Kampe" <thorsten@xxxxxxxxxxxxxxxx>:
> * ZyX (Sun, 12 Apr 2015 12:33:52 +0300)
>> 12.04.2015, 10:47, "Thorsten Kampe" <thorsten@xxxxxxxxxxxxxxxx>:
>>> Hi,
>>>
>>> Bash got negative length parameter expansion (like in `${STRING:11:-
>>> 17}`) in version 4.2 and Zsh in 4.3.12.
>>>
>>> How would I do negative length parameter expansion in Bash or Zsh if
>>> my version doesn't support it?
>> `$#STRING` is a length of the string. `-17` is `$(( ${#STRING}-17+1 ))`. (`$(( ))` may be not necessary, most likely they will not be necessary in zsh, don’t know about bash). `${#PARAMETER}` form is supported by any POSIX shell (but not `$#PARAMETER` without figure braces).
>
> Simple and elegant solution, thanks.
>
> Just for correctness: your solution has an off-by-one error (actually
> an "off by offset" error). Offset starts at 0. You're adding 1 but
> you would have to subtract 0 (or in general: offset).
Sorry, I was always using ${VAR[start,end]} form. My variant is correct for ${VAR[start,end]} (where `start` starts from one, not from zero), not for ${VAR:offset:length} which I never used (and thus for some reason was under impression that it was the other form of expressing the same thing).
Thanks for the correction.
>
> Following the example from
> <http://wiki.bash-hackers.org/syntax/pe#negative_length_value>
>
> ```
> MYSTRING="Be liberal in what you accept, and conservative in what you
> send"
> offset=11
> length=17
>
> printf "${MYSTRING:$offset:-$length}\n"
> in what you accept, and conservative
>
> length=$((${#MYSTRING} - offset - length))
> printf "${MYSTRING:$offset:$length}\n"
> in what you accept, and conservative
> ```
>
> Thorsten
Messages sorted by:
Reverse Date,
Date,
Thread,
Author