help-bash
[Top][All Lists]
Advanced

[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: Jesse Hathaway
Subject: Re: [Help-bash] Fastest way to join an array into a string
Date: Mon, 26 Aug 2019 16:31:15 -0500

This similar method as described on stackoverflow might be a bit
faster, but I haven't
benchmarked it, it does at least the virtue of not needing a parameter
expansion in the printf format string:

# https://stackoverflow.com/a/17841619/1236063
# $1 is the delimiter
# $2-n are the args to join
underpin::join_by() {
  local delimiter=$1
  shift
  echo -n "$1"
  shift
  # inserts the delimiter at the beginning of each arg
  printf '%s' "${@/#/$delimiter}"
}

On Mon, Aug 26, 2019 at 1:47 PM Peng Yu <address@hidden> wrote:
>
> Hi,
>
> 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.
>
>             echo -n "$1"
>             shift
>             if (($#)); then
>                 declare x
>                 printf "${separator//%/%%}%s" "$@"
>             fi
>
> --
> Regards,
> Peng
>



reply via email to

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