Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace empty element in bash array

Tags:

arrays

bash

shell

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
like image 727
stackoverflower Avatar asked Jan 27 '17 11:01

stackoverflower


2 Answers

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
like image 118
fedorqui 'SO stop harming' Avatar answered Oct 03 '22 21:10

fedorqui 'SO stop harming'


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
like image 32
Fred Avatar answered Oct 03 '22 21:10

Fred