替换bash数组中的空元素

编程入门 行业动态 更新时间:2024-10-25 22:32:08
本文介绍了替换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数组中的空元素

本文发布于:2023-11-10 15:43:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575781.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   元素   bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!