假设我创建了一个这样的数组:
IFS="|" read -ra ARR <<< "zero|one|||four"
现在
echo ${#ARR[@]}
> 5
echo "${ARR[@]}"
> zero one four
echo "${ARR[0]}"
> zero
echo "${ARR[2]}"
> # Nothing, because it is empty
问题是如何用另一个字符串替换空元素?
我试过了
${ARR[@]///other}
${ARR[@]//""/other}
它们都不起作用。
我想要这个作为输出:
zero one other other four
最佳答案
要让 shell 扩展正常运行,您需要遍历其元素并对每个元素执行替换:
$ IFS="|" read -ra ARR <<< "zero|one|||four"
$ for i in "${ARR[@]}"; do echo "${i:-other}"; done
zero
one
other
other
four
地点:
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
要将它们存储在一个新数组中,只需附加 +=( element )
即可:
$ new=()
$ for i in "${ARR[@]}"; do new+=("${i:-other}"); done
$ printf "%s\n" "${new[@]}"
zero
one
other
other
four
关于arrays - 替换 bash 数组中的空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893336/