명령의 출력을 연관 배열로 반환

명령의 출력을 연관 배열로 반환

명령의 출력을 연관 배열에 넣어야 합니다.

예를 들어:

dig mx +short google.com

다음을 반환합니다:

20 alt1.aspmx.l.google.com.
40 alt3.aspmx.l.google.com.
50 alt4.aspmx.l.google.com.
10 aspmx.l.google.com.
30 alt2.aspmx.l.google.com.

우선순위(10,20,...)를 키로, 레코드(aspmx.l.google.com.)를 값으로 사용하여 연관 배열을 만드는 방법은 무엇입니까?

답변1

해당 데이터를 bash 연관 배열로 읽는 한 가지 방법은 다음과 같습니다.

암호:

#!/usr/bin/env bash
declare -A hosts
while IFS=" " read -r priority host ; do
  hosts["$priority"]="$host"
done < <(dig mx +short google.com)    

for priority in "${!hosts[@]}" ; do
  echo "$priority -> ${hosts[$priority]}"
done

산출:

20 -> alt1.aspmx.l.google.com.
10 -> aspmx.l.google.com.
50 -> alt4.aspmx.l.google.com.
40 -> alt3.aspmx.l.google.com.
30 -> alt2.aspmx.l.google.com.

답변2

declare -A mx
eval $(dig mx +short google.com | sed "s/'//g; s/^/mx[/; s/ /]='/; s/$/';/")

명명된 연관 배열이 먼저 선언된 mx다음 실행되고 출력을 연관 배열 할당으로 변환하는 dig데 사용되며 , 그런 다음 현재 쉘로 변환됩니다. 이 명령은 모든 작은따옴표를 제거한 다음 값을 참조하기 위해 작은따옴표를 사용하여 변수 할당을 래핑합니다.sedevalsed

답변3

첫째, Stephen Rauch의 솔루션(및 Cheppner의 의견)이 훌륭하다고 생각합니다. 그러나 그것에 관해서는연관 배열, 나는 거의 항상 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의 또 다른 예일 뿐이며 그 이상은 아닙니다.

답변4

내부 필드 구분 기호를 사용하여 입력을 줄로 구분할 수 있습니다.

 IFS="\n" read -ra ADDR <<< "$IN"

관련 정보