[Top][All Lists]

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

Re: [Help-bash] Using slices with arrays

From: Nick Chambers
Subject: Re: [Help-bash] Using slices with arrays
Date: Wed, 4 Oct 2017 20:10:37 +0000

On 10/4/17, 3:09 PM, "Greg Wooledge" <address@hidden> wrote:

>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
>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>

Perfect. Thank you!

reply via email to

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