Imagine I created an array like this:
IFS="|" read -ra ARR <<< "zero|one|||four"
now
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?
I have tried
${ARR[@]///other}
${ARR[@]//""/other}
none of them worked.
I want this as output:
zero one other other four
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
Where:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
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
If you want to replace all empty values (actually modifying the list), you could do this :
for i in "${!ARR[@]}" ; do ARR[$i]="${ARR[$i]:-other}"; done
Which looks like this when indented (more readable I would say) :
for i in "${!ARR[@]}"
do
ARR[$i]="${ARR[$i]:-other}"
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With