From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 4206 invoked by alias); 12 Apr 2015 11:44:02 -0000 Mailing-List: contact zsh-users-help@zsh.org; run by ezmlm Precedence: bulk X-No-Archive: yes List-Id: Zsh Users List List-Post: List-Help: X-Seq: 20141 Received: (qmail 28713 invoked from network); 12 Apr 2015 11:43:42 -0000 X-Spam-Checker-Version: SpamAssassin 3.3.2 (2011-06-06) on f.primenet.com.au X-Spam-Level: X-Spam-Status: No, score=-2.6 required=5.0 tests=BAYES_00,RCVD_IN_DNSWL_LOW, SPF_HELO_PASS autolearn=ham version=3.3.2 X-Injected-Via-Gmane: http://gmane.org/ To: zsh-users@zsh.org From: Thorsten Kampe Subject: Re: Negative length parameter expansion Date: Sun, 12 Apr 2015 13:43:24 +0200 Message-ID: References: <2421271428831232@web29o.yandex.ru> Mime-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit X-Complaints-To: usenet@ger.gmane.org X-Gmane-NNTP-Posting-Host: p5de5aada.dip0.t-ipconnect.de User-Agent: MicroPlanet-Gravity/3.0.4 * ZyX (Sun, 12 Apr 2015 12:33:52 +0300) > > 12.04.2015, 10:47, "Thorsten Kampe" : > > 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). Following the example from ``` 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