本文介绍了替换bash数组中的空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下我创建了一个像这样的数组:
Imagine I created an array like this:
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问题是如何将空元素替换为另一个字符串?
The question is how can I replace the empty elements with another string?
我尝试过
${ARR[@]///other} ${ARR[@]//""/other}他们都没有工作.
我希望将此作为输出
zero one other other four推荐答案
要使shell扩展起作用,您需要遍历其元素并对每个元素进行替换:
To have the shell expansion behave, you need to loop through its elements and perform the replacement on each one of them:
$ IFS="|" read -ra ARR <<< "zero|one|||four" $ for i in "${ARR[@]}"; do echo "${i:-other}"; done zero one other other four位置:
$ {parameter:-word}
如果参数未设置或为null,则替换单词的扩展名.否则,将替换参数的值.
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
要将它们存储在新数组中,只需添加+=( element ):
To store them in a new array, just do so by appending with +=( element ):
$ new=() $ for i in "${ARR[@]}"; do new+=("${i:-other}"); done $ printf "%s\n" "${new[@]}" zero one other other four更多推荐
替换bash数组中的空元素
发布评论