Прежде всего, я думаю, что решение Стивена Рауха (наряду с комментарием Чепнера) замечательное. Но когда дело доходит до ассоциативных массивов, я почти всегда использую словари в Python, не потому что мне не нравится Bash, а потому что с ними (на мой взгляд) проще работать на языке более высокого уровня.
Ниже приведен пример использования в 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)
Выполнение:
./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."
}
Опять же, решение выше в Bash - отличное (и проголосованное мной). Это просто еще один пример на Python, не более того.