[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Fastest way to join an array into a string
From: |
Stephane Chazelas |
Subject: |
Re: [Help-bash] Fastest way to join an array into a string |
Date: |
Mon, 26 Aug 2019 22:18:02 +0100 |
User-agent: |
NeoMutt/20171215 |
2019-08-26 13:58:34 -0500, Peng Yu:
> On Mon, Aug 26, 2019 at 1:55 PM Quentin L'Hours <address@hidden> wrote:
[...]
> > On 2019-08-26 11:47 a.m., Peng Yu wrote:
> > > I'd like to do something similar to str.join() in python.
> > >
> > > Suppose the array is in $@, I currently use the following code to
> > > print the joined result ($separator contains the separator to join the
> > > string). Is it the fastest way to do so in bash? Thanks.
> >
> > You could use "$*" which is a single string of all the args separated by
> > the first letter of the IFS:
> >
> > $ set a b c
> > $ IFS=/
> > $ printf '%s\n' "$*"
> > a/b/c
>
> It doesn't work if the separator is a string of more than one characters.
[...]
Then maybe:
join_into() {
local -n _var="$1"
local IFS= _sep="$2" _first="$3"
shift "$(($# > 2 ? 3 : 2))"
_var=$_first${*/#/$_sep}
}
join_into var sep "${myarray[@]}"
Note that the zsh shell has a builtin operator (parameter
expansion flag) for that:
var=${(j:sep:)myarray}
And the fish shell a shell builtin:
set var (string join sep $myarray)
--
Stephane