Bash字符串处理-13.字符串数组连接(二)

2014-11-24 02:53:11 · 作者: · 浏览: 4
local sep="$1"
shift
local dst
for s in "$@"
do
if [ "$dst" ]; then
dst=${dst}${sep}${s}
else
dst=${s}
fi
done
echo "$dst"
}

正确:str_join_sep "$SEP" "$ARR[@]"
注意双引号的使用。

[root@jfht ~]# declare -f str_join_sep
str_join_sep ()
{
local sep="$1";
shift;
local dst;
for s in "$@";
do
if [ "$dst" ]; then
dst=${dst}${sep}${s};
else
dst=${s};
fi;
done;
echo "$dst"
}
[root@jfht ~]# ARR=(yes no 'hello world')
[root@jfht ~]# SEP=,
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes,no,hello world
[root@jfht ~]#

实现方式二
str_join_sep ()
{
local sep="$1"
shift
local dst="$1"
shift
for s in "$@"
do
dst=${dst}${sep}${s}
done
echo "$dst"
}

[root@jfht ~]# declare -f str_join_sep
str_join_sep ()
{
local sep="$1";
shift;
local dst="$1";
shift;
for s in "$@";
do
dst=${dst}${sep}${s};
done;
echo "$dst"
}
[root@jfht ~]# ARR=(yes no 'hello world')
[root@jfht ~]# SEP=,
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes,no,hello world
[root@jfht ~]# SEP=:
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes:no:hello world
[root@jfht ~]# SEP='|'
注意加上单引号,否则Bash认为是管道线。
[root@jfht ~]# str_join_sep "$SEP" "${ARR[@]}"
yes|no|hello world
[root@jfht ~]#

作者“Bash @ Linux