Replace empty element in bash array

Imagine that 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 to replace empty elements with another line?

I tried

 ${ARR[@]///other} ${ARR[@]//""/other} 

none of them worked.

I want this as a conclusion:

 zero one other other four 
+5
source share
2 answers

To have a shell extension, you need to loop through its elements and replace on each 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 the parameter is not specified or is null, the word is replaced. Otherwise, the parameter value will be replaced.

To save them in a new array, just do it by adding with +=( element ) :

 $ new=() $ for i in "${ARR[@]}"; do new+=("${i:-other}"); done $ printf "%s\n" "${new[@]}" zero one other other four 
+4
source

If you want to replace all empty values ​​(actually modifying the list), you can do this:

 for i in "${!ARR[@]}" ; do ARR[$i]="${ARR[$i]:-other}"; done 

It looks like the indentation (more readable, I would say):

 for i in "${!ARR[@]}" do ARR[$i]="${ARR[$i]:-other}" done 
+3
source

Source: https://habr.com/ru/post/1263440/


All Articles