替换bash数组中的空元素 [英] Replace empty element in bash array

查看:138
本文介绍了替换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数组中的空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆