Filter based index array in bash

Issue

I need to find a way to filter the variables of an array, following the index of each variable.
So far I only have the following example.

DATA[nidforusr1]='jamaica'
DATA[nidforusr2]='brasil'
DATA[nidforusr3]='janaina'
DATA[nidforusr4]='cebola'
DATA[nidforusr5]='batata' 
DATA[nidforbkp1]='ketchup'
DATA[pwforusr1]='sorvete'
DATA[pwforusr2]='google'
DATA[pwforusr3]='pesado'
DATA[pwforusr4]='maluco'
DATA[pwforusr5]='programador'
DATA[pwforbkp1]='macaco'
DATA[ipforusr1]='batata'
DATA[ipforusr2]='senha'
DATA[ipforusr3]='microfone'
DATA[ipforusr4]='passarinho'
DATA[ipforusr5]='abobora'
DATA[ipforbkp1]='caixa'

for ((i=0;i<=${#DATA[@]};i++))
do
    echo "${DATA[@]:nidforusr1:nidforusr*}"
done

---------------- OR ------------------

for i in ${!DATA[@]}
do
  if [[ "$i" == "nidforusr*" ]]
  then
    echo "${DATA[i]}"
  fi
done

I want to filter the contents of array, but only the contents of array variable that start with index nidforusr

Here’s the challenge.

Solution

If you fix the position of * and change [i] to [$i], it should work.

declare -A DATA

DATA[nidforusr1]='jamaica'
DATA[nidforusr2]='brasil'
DATA[nidforusr3]='janaina'
DATA[nidforusr4]='cebola'
DATA[nidforusr5]='batata' 
DATA[nidforbkp1]='ketchup'
DATA[pwforusr1]='sorvete'
DATA[pwforusr2]='google'
DATA[pwforusr3]='pesado'
DATA[pwforusr4]='maluco'
DATA[pwforusr5]='programador'
DATA[pwforbkp1]='macaco'
DATA[ipforusr1]='batata'
DATA[ipforusr2]='senha'
DATA[ipforusr3]='microfone'
DATA[ipforusr4]='passarinho'
DATA[ipforusr5]='abobora'
DATA[ipforbkp1]='caixa'

for i in ${!DATA[@]}
do
  if [[ "$i" == "nidforusr"* ]]
  then
    echo "${DATA[$i]}"
  fi
done

Answered By – etsuhisa

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published