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: alex xmb sw ratchev
Subject: Re: (question) fast split/join of strings
Date: Tue, 17 Sep 2024 16:07:58 +0200

savedifs=${IFS@A} savedifs=${savedifs:- unset -v IFS }
str=1,2,3 IFS=, arr=( $str ) joined=${arr[*]}
eval "$savedifs"

alternative middleline

sep=, str=1$sep2$sep3 IFS=$sep arr=( $str ) joined=${arr[*]}

( at var=assignment , quotes dont matter , excepts to bind spaced code
together
as cmd or cmd args , or array=( here element ) , use quotes around the args
, eg "$cmd" "$arg" "${argarr[@]}" ; arr=( "$var" "${vararr[@]}" )
 )

to join via first of IFS , as one-string , ${arr[*]}
to join the elements as args , "${arr[@]}"
to do this via printf , two cmds are needed ( there are serval approaches )
one is cutting runaway ,
 {
printf -v joined2 %s, "${arr[@]}"
joined2=${joined2%,}
 }

with printf only , and to stdout
 {
printf %s "$arr"
printf "$sep%s" "${arr[@]:1}"
 # -- same as ( second printf )
# printf ,%s "${arr[@]:1}"
 }

there is alternatively an inline way to split strings containing quotes and
backslashes
eg {
str="1" "2" "3"'
declare -a "split=( $str )"
 }

greets

On Tuesday, September 17, 2024, William Park <opengeometry@yahoo.ca> wrote:

> Hi all,
>
> Is there fast way of splitting and joining of strings in the recent Bash
> versions?
>
> For splitting, I'm aware of
>     old="a,b,c"
>     IFS=, read -a arr <<< "$old"
>
> For joining,
>     new=$(IFS=,; echo "${arr[*]}")
> or
>     new=$(IFS=,; echo "$*")
>
>
>


reply via email to

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