替换bash数组中的空元素

sta*_*wer 5 arrays bash shell

想象一下,我创建了一个这样的数组:

IFS="|" read -ra ARR <<< "zero|one|||four"
Run Code Online (Sandbox Code Playgroud)

现在

echo ${#ARR[@]}
> 5
echo "${ARR[@]}"
> zero one   four
echo "${ARR[0]}"
> zero
echo "${ARR[2]}"
> # Nothing, because it is empty
Run Code Online (Sandbox Code Playgroud)

问题是如何用另一个字符串替换空元素?

我试过了

${ARR[@]///other}
${ARR[@]//""/other}
Run Code Online (Sandbox Code Playgroud)

他们都没有工作.

我希望这个输出:

zero one other other four
Run Code Online (Sandbox Code Playgroud)

fed*_*qui 4

要使 shell 扩展正常运行,您需要循环遍历其元素并对每个元素执行替换:

$ IFS="|" read -ra ARR <<< "zero|one|||four"
$ for i in "${ARR[@]}"; do echo "${i:-other}"; done
zero
one
other
other
four
Run Code Online (Sandbox Code Playgroud)

在哪里:

${参数:-word}

如果参数未设置或为空,则替换单词的扩展。否则,将替换参数的值。

要将它们存储在新数组中,只需附加以下内容即可+=( element )

$ new=()
$ for i in "${ARR[@]}"; do new+=("${i:-other}"); done
$ printf "%s\n" "${new[@]}"
zero
one
other
other
four
Run Code Online (Sandbox Code Playgroud)