如何在 Bash 中加入数组的元素? [英] How can I join elements of an array in Bash?

查看:27
本文介绍了如何在 Bash 中加入数组的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Bash 中有一个这样的数组:

If I have an array like this in Bash:

FOO=( a b c )

如何用逗号连接元素?例如,产生 a,b,c.

How do I join the elements with commas? For example, producing a,b,c.

推荐答案

一个支持多字符分隔符的 100% 纯 Bash 函数是:

A 100% pure Bash function that supports multi-character delimiters is:

function join_by { local d=${1-} f=${2-}; if shift 2; then printf %s "$f" "${@/#/$d}"; fi; }

例如

join_by , a b c #a,b,c
join_by ' , ' a b c #a , b , c
join_by ')|(' a b c #a)|(b)|(c
join_by ' %s ' a b c #a %s b %s c
join_by $'\n' a b c #a<newline>b<newline>c
join_by - a b c #a-b-c
join_by '\' a b c #a\b\c
join_by '-n' '-e' '-E' '-n' #-e-n-E-n-n
join_by , #
join_by , a #a

以上代码基于@gniourf_gniourf、@AdamKatz、@MattCowell 和@x-yuri 的想法.它适用于选项 errexit (set -e) 和 nounset (set -u).

The code above is based on the ideas by @gniourf_gniourf, @AdamKatz, @MattCowell, and @x-yuri. It works with options errexit (set -e) and nounset (set -u).

或者,一个仅支持单个字符分隔符的更简单的函数是:

Alternatively, a simpler function that supports only a single character delimiter, would be:

function join_by { local IFS="$1"; shift; echo "$*"; }

例如

join_by , a "b c" d #a,b c,d
join_by / var local tmp #var/local/tmp
join_by , "${FOO[@]}" #a,b,c

此解决方案基于 Pascal Pilz 的原始建议.

This solution is based on Pascal Pilz's original suggestion.

之前在这里提出的解决方案的详细解释可以在 如何在 bash 脚本中加入 () 数组元素",meleudev.to 上的一篇文章.

A detailed explanation of the solutions previously proposed here can be found in "How to join() array elements in a bash script", an article by meleu at dev.to.

这篇关于如何在 Bash 中加入数组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆