如果我在Bash中有一个这样的数组:
FOO=( a b c )
如何用逗号连接元素?例如,生成a b c。
如果我在Bash中有一个这样的数组:
FOO=( a b c )
如何用逗号连接元素?例如,生成a b c。
当前回答
liststr=""
for item in list
do
liststr=$item,$liststr
done
LEN=`expr length $liststr`
LEN=`expr $LEN - 1`
liststr=${liststr:0:$LEN}
这也可以处理结尾多余的逗号。我不是bash专家。只是我的2c,因为这更基本,更容易理解
其他回答
也许,例如,
SAVE_IFS="$IFS"
IFS=","
FOOJOIN="${FOO[*]}"
IFS="$SAVE_IFS"
echo "$FOOJOIN"
现在我用的是:
TO_IGNORE=(
E201 # Whitespace after '('
E301 # Expected N blank lines, found M
E303 # Too many blank lines (pep8 gets confused by comments)
)
ARGS="--ignore `echo ${TO_IGNORE[@]} | tr ' ' ','`"
这是可行的,但是(在一般情况下)如果数组元素中有空格,将会严重破坏。
(对于那些感兴趣的人,这是一个围绕pep8.py的包装器脚本)
$ set a 'b c' d
$ history -p "$@" | paste -sd,
a,b c,d
liststr=""
for item in list
do
liststr=$item,$liststr
done
LEN=`expr length $liststr`
LEN=`expr $LEN - 1`
liststr=${liststr:0:$LEN}
这也可以处理结尾多余的逗号。我不是bash专家。只是我的2c,因为这更基本,更容易理解
这种方法处理值中的空格,但需要一个循环:
#!/bin/bash
FOO=( a b c )
BAR=""
for index in ${!FOO[*]}
do
BAR="$BAR,${FOO[$index]}"
done
echo ${BAR:1}