在字符串数组中插入空格

Insert spaces in the string array

我有以下数组:

declare -a case=("060610" "080813" "101016" "121219" "141422")

我想生成另一个数组,其中的元素适当地插入了空格,如:

"06 06 10" "08 08 13" "10 10 16" "12 12 19" "14 14 22"

我直到使用 sed 单独处理元素:

echo '060610' | sed 's/../& /g'

但是我在使用数组时无法做到这一点。 sed 混淆了元素之间的空格,我只剩下输出:

echo "${case[@]}" | sed 's/../& /g'

给我:

06 06 10  0 80 81 3  10 10 16  1 21 21 9  14 14 22

有人可以帮忙吗?

您需要遍历数组,而不是将其作为一个整体回显,因为回显时不会得到分组。

declare -a newcase
for c in "${case[@]}"
do
    newcase+=("$(echo "$c" | sed 's/../& /g')")
done

您可以使用 printf '%s\n' "${case[@]}" | sed 's/../& /g' 将每个数字放在单独的行上并避免 space 问题:

$ declare -a case=("060610" "080813" "101016" "121219" "141422")

$ printf '%s\n' "${case[@]}" | sed 's/../& /g'
06 06 10
08 08 13
10 10 16
12 12 19
14 14 22

如果你想把它放回一个数组中,你可以使用mapfile