0

I have an associative array that I create from a file for getting failed login attemps per user. The array looks like this:

declare -Ai hash

while read -r -a array; do
    [[ "${array[5]} ${array[6]}" == "Failed password" ]] && hash[${array[8]}]+=1
done < $FILEPATH

One of the users that comes up is listed as invalid and I'd like to change the string to UNKNOWN. So how do I iterate over the hash and find the string I need and replace its value?

Something like this?

for i in "${!hash[@]}"; do
    # (if $i == 'invalid', replace with 'UNKNOWN') ??
done

What would be the syntax for that replace?

user3066571
  • 1,381
  • 4
  • 14
  • 37
  • you want to compare `"${array[8]}"` to "invalid", and if they're the same, set `array[8]` the string "UNKNOWN"? Does https://stackoverflow.com/questions/4277665/how-do-i-compare-two-string-variables-in-an-if-statement-in-bash help? – that other guy Jan 27 '18 at 22:58
  • This looks like you're changing the string *in your input*, not in your associative array... right? I don't see how the associative array is actually related to your question about updating values. – Charles Duffy Jan 27 '18 at 22:58
  • @CharlesDuffy you could be right, maybe I'm coming at this wrong. Is it possible to pipe and replace the string I care about as I'm passing it in? i.e. `done < $FILEPATH | sed -i 's/invalid/UNKNOWN/g'` ? – user3066571 Jan 27 '18 at 23:10
  • `done < <(sed 's/invalid/UNKNOWN/g' <"$FILEPATH")`, but I still don't see why you're trying to change something in the *associative* array instead of the *indexed* array. – Charles Duffy Jan 27 '18 at 23:10
  • ie. `[[ ${array[7]} = invalid ]] && array[7]=UNKNOWN; [[ ${array[8]} = invalid ]] && array[8]=UNKNOWN` is AFAIK doing what you want, but by changing the *indexed* array `array`, instead of the *associative* array `hash`. – Charles Duffy Jan 27 '18 at 23:12
  • (that said, I'm not really convinced that you're getting value from using an indexed array here at all, instead of something like `while read -r _ _ _ _ _ _ fname lname _` or such, if in fact the fields you're reading are first and last name). – Charles Duffy Jan 27 '18 at 23:15
  • @CharlesDuffy: see https://stackoverflow.com/a/48480547/3776858 – Cyrus Jan 27 '18 at 23:43

2 Answers2

2

Something that pops in my mind is creating a copy of the element with UNKNOWN

hash[UNKNOWN]=hash[invalid]
unset hash[invalid]
kvantour
  • 25,269
  • 4
  • 47
  • 72
1

If I understand correctly, you could do:

hash[UNKNOWN]=${hash[invalid]}
unset hash[invalid]
rici
  • 234,347
  • 28
  • 237
  • 341