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

查看:187
本文介绍了如何在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.

推荐答案

Pascal Pilz将解决方案重写为100%纯Bash中的函数(无外部命令):

Rewriting solution by Pascal Pilz as a function in 100% pure Bash (no external commands):

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

或者,我们可以使用@gniourf_gniourf的想法,使用printf支持多字符定界符

Alternatively, we can use printf to support multi-character delimiters, using the idea by @gniourf_gniourf

function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; }

例如,

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

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

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