bug-bash
[Top][All Lists]
Advanced

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

Re: (question) fast split/join of strings


From: Greg Wooledge
Subject: Re: (question) fast split/join of strings
Date: Tue, 17 Sep 2024 10:20:02 -0400

On Tue, Sep 17, 2024 at 16:07:58 +0200, alex xmb sw ratchev wrote:
> savedifs=${IFS@A} savedifs=${savedifs:- unset -v IFS }
> str=1,2,3 IFS=, arr=( $str ) joined=${arr[*]}
> eval "$savedifs"

Using unquoted $str in an array expansion to do the splitting has a
couple drawbacks:

1) Globbing (filename expansion) is done unless you turn it off.

    hobbit:~$ str=1,2,*.xml,4
    hobbit:~$ IFS=, arr=( $str ); declare -p arr
    declare -a arr=([0]="1" [1]="2" [2]="passwd.5.xml" [3]="4")

   Workaround: set -f, but now you have an extra shell setting to
   manage (do you do a set +f later, or do you wrap it in a function
   and try to use "local -", or do you use a subshell, or do you simply
   leave globbing disabled for the whole script...).

2) Pitfall 47 still applies.

    hobbit:~$ bash
    hobbit:~$ str=1,2,,4,
    hobbit:~$ IFS=, arr=( $str ); declare -p arr
    declare -a arr=([0]="1" [1]="2" [2]="" [3]="4")

   Same workaround as all the others -- add an extra delimiter to the
   end of the input string before splitting it.  If there is no empty
   field at the end, then the extra delimiter gets eaten.  If there
   is an empty field, then the extra delimiter preserves it before
   being eaten.



reply via email to

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