help-bash
[Top][All Lists]
Advanced

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

Re: String to array


From: Greg Wooledge
Subject: Re: String to array
Date: Thu, 30 Sep 2021 11:41:28 -0400

On Thu, Sep 30, 2021 at 10:39:36AM -0400, Greg Wooledge wrote:
> (*) Element 10 $'\n\E' is wrong, so it didn't actually work.  I suppose
>     I need to write some messages for the other list now.

The newline thing is due to sed.  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.

As it turns out, perl's pretty good at this.  But it *also* has an issue
with newlines that took me some time to dig up.  From "perldoc perlre":

     .   Match any single character except newline    Not in []
           (under /s, includes newline)

So, here we go:

unicorn:~$ string=$'hi bye\twhy\n\e[;1'
unicorn:~$ string="$string" perl -e '$_=$ENV{"string"}; s/./$&\000/gs; print' | 
hd
00000000  68 00 69 00 20 00 62 00  79 00 65 00 09 00 77 00  |h.i. .b.y.e...w.|
00000010  68 00 79 00 0a 00 1b 00  5b 00 3b 00 31 00        |h.y.....[.;.1.|
0000001e

That looks usable.  The newline and escape are not crammed together
the way they were under sed, or under perl when I didn't know I had
to use /gs instead of /g.

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

The usual disclaimer applies: if you have to invoke perl from your bash
script, you should just write the whole damned thing in perl instead.



reply via email to

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