Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dictionary from a text file in bash?

I want to create a dictionary in bash from a text file which looks like this:

H96400275|A
H96400276|B
H96400265|C
H96400286|D

Basically I want a dictionary like this from this file file.txt:

KEYS        VALUES
H96400275 = A
H96400276 = B
H96400265 = C
H96400286 = D

I created following script:

#!/bin/bash
declare -a dictionary

while read line; do 

  key=$(echo $line | cut -d "|" -f1)
  data=$(echo $line | cut -d "|" -f2)
  dictionary[$key]="$data"
done < file.txt


echo ${dictionary[H96400275]}

However, this does not print A, rather it prints D. Can you please help ?

like image 869
lakhujanivijay Avatar asked Jan 30 '26 03:01

lakhujanivijay


1 Answers

Associative arrays (dictionaries in your terms) are declared using -A, not -a. For references to indexed (ones declared with -a) arrays' elements, bash performs arithmetic expansion on the subscript ($key and H96400275 in this case); so you're basically overwriting dictionary[0] over and over, and then asking for its value; thus D is printed.

And to make this script more effective, you can use read in conjunction with a custom IFS to avoid cuts. E.g:

declare -A dict

while IFS='|' read -r key value; do
    dict[$key]=$value
done < file

echo "${dict[H96400275]}"

See Bash Reference Manual § 6.7 Arrays.

like image 169
oguz ismail Avatar answered Feb 02 '26 02:02

oguz ismail