击:加入一个数组中的元素? [英] Bash: Join elements of an array?

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

问题描述

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

If I have an array like this in Bash:

FOO=( a b c )

我如何加入用逗号分隔的元素?例如,生产 A,B,C

推荐答案

由Pascal皮尔磁重写解决方案为100%纯猛砸功能(无外部命令):

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

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

例如,

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

另外,我们可以通过@gniourf_gniourf

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

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

例如,

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

此外,你应该调用这个函数joinStrings以避免与标准的Unix命令加入冲突。

Also, you should really call this function joinStrings to avoid clashing with the standard Unix command "join".

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

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