help-bash
[Top][All Lists]
Advanced

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

Re: String to array


From: Tapani Tarvainen
Subject: Re: String to array
Date: Sat, 2 Oct 2021 10:25:58 +0300

On Thu, Sep 30, 2021 at 11:41:28AM -0400, Greg Wooledge (greg@wooledge.org) 
wrote:

> As is customary, any time I encounter a problem with sed,
> *especially* if it involves newlines, I just toss sed out and use
> something else.

:-)

> unicorn:~$ mapfile -d '' array < <(string="$string" perl -e 
> '$_=$ENV{"string"}; s/./$&\000/gs; print')
> unicorn:~$ declare -p array
> declare -a array=([0]="h" [1]="i" [2]=" " [3]="b" [4]="y" [5]="e" [6]=$'\t' 
> [7]="w" [8]="h" [9]="y" [10]=$'\n' [11]=$'\E' [12]="[" [13]=";" [14]="1")
> 
> (There may be some way to do it with sed, but I don't have the patience
> to try to figure it out.  Suffice to say, sed 's/./&\000/g' is definitely
> not it.)

Yeah. If sed is bad with newlines, it's even worse with NULs.

And of course perl can do anything. :-)

But, here're a couple more possibilities:

mapfile -t array < <(fold -w 1 <<<$string)

I rather like that one, even though it still fails with newlines.

This one handles newlines correctly:

eval inds=({1..${#string}})
mapfile -t -d '' array < <(cut -z -c "${inds[*]}" --output-delimiter=$'\000' 
<<<$string)

Annoyingly it needs that brace expansion eval thing, because cut
doesn't have any repeat option that'd work here.

-- 
Tapani Tarvainen



reply via email to

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