[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Using slices with arrays

From: Greg Wooledge
Subject: Re: [Help-bash] Using slices with arrays
Date: Wed, 4 Oct 2017 16:09:12 -0400
User-agent: NeoMutt/20170113 (1.7.2)

On Wed, Oct 04, 2017 at 08:02:23PM +0000, Nick Chambers wrote:
> Hello all! I am using bash4.4 and have some questions about slices in bash. 
> For my first example:
> NickChambers-iMac:~ Nick$ str='this is a message'
> NickChambers-iMac:~ Nick$ echo "${str:4:(-1)}"
>  is a messag
> NickChambers-iMac:~ Nick$
> This clearly allows a negative index,

But it's not necessary.  You can simply use "${str:4}" to get the substring
from position 4 to the end.

wooledg:~$ str="this is a message"
wooledg:~$ echo "${str:4}"
 is a message

> but if I try to do the same thing with an array, I get the following:
> NickChambers-iMac:~ Nick$ colors=(purple blue orange yellow green)
> NickChambers-iMac:~ Nick$ echo "address@hidden:1:(-1)}"
> -bash: (-1): substring expression < 0

Again, you just omit the length argument if you want to go all the way
to the end.

wooledg:~$ colors=(purple blue orange yellow green)
wooledg:~$ args "address@hidden:1}"
4 args: <blue> <orange> <yellow> <green>

> Also, incidentally, is there a better way to span from an index to the end of 
> the string besides using something like the following:

Just omit the length.

Only specify a length when you want (at most) that many elements.

wooledg:~$ args "address@hidden:1:2}"
2 args: <blue> <orange>
wooledg:~$ args "address@hidden:3:1}"
1 args: <yellow>

reply via email to

[Prev in Thread] Current Thread [Next in Thread]