On Mon, 2 Feb 2026, Greg Wooledge wrote:

> On Tue, Feb 03, 2026 at 01:19:35 +0000, [email protected] wrote:
>> On Mon, 2 Feb 2026, Greg Wooledge wrote:
>>
>>> On Mon, Feb 02, 2026 at 23:30:16 +0000, [email protected] wrote:
>>>> don't know what he meant
>>>> https://stackoverflow.com/questions/7578930/bash-split-string-into-character-array
>>>
>>> Oh, so you didn't actually WRITE the code.
>>>
>>> Was your question "How does this code work?"
>>
>> yes
>
> OK, here's the code once again:
>
>    string='whatever'
>    [[ $string =~ ${string//?/(.)} ]]
>    array=( "${BASH_REMATCH[@]:1}" )
>
> The first line is just assigning the input, which in a real script
> would come from somewhere other than the script itself.
>
> The second line is really doing two things.  It's been written as a
> single line for brevity.  Let's break it apart:
>
>    re=${string//?/(.)}
>    [[ $string =~ $re ]]
>
> I've inserted the temporary variable "re" here, to hold a regular
> expression.  This is the real magic.  "re" contains a regexp which
> has one instance of "(.)" for every character in the input string.
> For example, if the input string has 8 characters, the re has 24.
>
>    hobbit:~$ string='whatever'
>    hobbit:~$ re=${string//?/(.)}
>    hobbit:~$ declare -p re
>    declare -- re="(.)(.)(.)(.)(.)(.)(.)(.)"
>
> The [[ command with =~ operator matches a string (the left hand side)
> against an Extended Regular Expression (the right hand side).
>
>    [[ $string =~ $re ]]
>
> expands to
>
>    [[ whatever =~ (.)(.)(.)(.)(.)(.)(.)(.) ]]
>
> Each (.) is a single-character wildcard match with parentheses around it,
> meaning it's captured as a substring.  The first (.) captures the w,
> the second captures the h, the third captures the a, and so on.
>
> After a [[ command with =~ operator has completed, the BASH_REMATCH
> array will be populated with the substring that matched the full
> regular expression (index 0), and then each captured substring
> (index 1 and beyond).
>
>    hobbit:~$ [[ $string =~ $re ]]
>    hobbit:~$ declare -p BASH_REMATCH
>    declare -a BASH_REMATCH=([0]="whatever" [1]="w" [2]="h" [3]="a" [4]="t" 
> [5]="e" [6]="v" [7]="e" [8]="r")
>
> Finally, we have
>
>    array=( "${BASH_REMATCH[@]:1}" )
>
> which simply copies the elements of the BASH_REMATCH array starting
> at index 1 into the output array variable.
>
>    hobbit:~$ array=( "${BASH_REMATCH[@]:1}" )
>    hobbit:~$ declare -p array
>    declare -a array=([0]="w" [1]="h" [2]="a" [3]="t" [4]="e" [5]="v" [6]="e" 
> [7]="r")
>

a feast for thought
thanks

Reply via email to