First of all, I think Stephen Rauch's solution (alongside chepner's comment) is great. But when it comes to associative arrays, I almost always use dictionaries in Python, not because I don't like Bash, but because they are (in my opinion) easier to work with in a higher level language.
Below is an example of usage in Python.
#!/usr/bin/env python3
import subprocess
import os
import json
digDict = {}
tmpOut = open("tmpOut", "w")
output = subprocess.call(['dig', 'mx', '+short', 'google.com'], stdout=tmpOut)
# Fill the dictionary with the values we want
with open("tmpOut") as infile:
for line in infile:
digDict[line.split()[0]] = line.split()[1]
os.remove("tmpOut")
# Sort the dictionary by key
print("Sorted dictionary:")
for key in sorted(digDict):
print(key + " -> " + digDict[key])
# Get a specific value based on key
print("Access value associated with key '10' (digDict[\"10\"]):")
print(digDict["10"])
# "Pretty print" the dictionary in json format
print("json format:")
print(json.dumps(digDict, sort_keys=True, indent=4))
# Saved the dictionary to file in json format
with open("digDict.json", "w") as fp:
json.dump(digDict, fp, sort_keys=True, indent=4)
exit(0)
Execution:
./myDig.py
Sorted dictionary:
10 -> aspmx.l.google.com.
20 -> alt1.aspmx.l.google.com.
30 -> alt2.aspmx.l.google.com.
40 -> alt3.aspmx.l.google.com.
50 -> alt4.aspmx.l.google.com.
Access value associated with key '10' (digDict["10"]):
aspmx.l.google.com.
json format:
{
"10": "aspmx.l.google.com.",
"20": "alt1.aspmx.l.google.com.",
"30": "alt2.aspmx.l.google.com.",
"40": "alt3.aspmx.l.google.com.",
"50": "alt4.aspmx.l.google.com."
}
cat digDict.json
:
{
"10": "aspmx.l.google.com.",
"20": "alt1.aspmx.l.google.com.",
"30": "alt2.aspmx.l.google.com.",
"40": "alt3.aspmx.l.google.com.",
"50": "alt4.aspmx.l.google.com."
}
Again; the solution above in Bash is great (and upvoted by me). This is just another example in Python, nothing more.