[英]Compare keys in json string using Unix shell script
我有一個要求,我需要使用Unix Shell腳本比較兩個字符串中的鍵。 我正在使用源字符串創建json字符串,因此我需要確保源字符串中的所有鍵都存在於Json字符串中。 也就是說,鍵8、35、79、80、44、33和10應該存在於Json字符串中。 json字符串也可以嵌套。
源字符串樣本 : 8=FIX|35=c|79=1|80=5|31=2|44=TEST|33=1.0|10=Test
json范例 : {"8":"FIX", "35":"c", "79":[{"80":"5","31":"2"}], "33":"1.0", "44":"TEST", "10":"Test"}
我看到許多關於jq的示例,但是現在不能使用jq。 誰能幫我解決這個問題?
您可以為兩個輸入中的每個輸入創建一個鍵數組,並將它們與嵌套的for循環進行比較。 這適用於您的示例:
#!/bin/bash
EXIT_STATUS=0
String1="8=FIX|35=c|79=1|80=5|31=2|44=TEST|33=1.0|10=Test"
String2="{8:FIX, 35:c, 79:[{80:5,31:2}], 33:1.0, 44:TEST, 10:Test}"
String1_keys=($(echo "$String1" | sed -e 's/=[^|]*|/ /g' -e 's/=.*//g'))
String2_keys=($(echo "$String2" | sed -e 's/:\[/:nested, [/g' -e's/[{}\[\]]*//g' -e 's/:[^,]*,/ /g' -e 's/:.*$//g'))
for key1 in ${String1_keys[*]}; do
keyFound=0
for key2 in ${String2_keys[*]}; do
if [ "$key1" == "$key2" ]; then
keyFound=1
break
fi
done
if [ $keyFound -eq 0 ]; then
echo "key $key1 does not exist in String2_keys" 2>&1
EXIT_STATUS=1
fi
done
if [ $EXIT_STATUS -eq 0 ]; then
echo "All keys in String1_keys exist in String2_keys"
fi
exit $EXIT_STATUS
根據您要輸入的字符串的格式,可能需要修改第9行和第10行上的sed語句。
如果要獲取每個字符串中唯一鍵的數量,請參考以下兩個想法(我相信這很容易成為地獄):
#!/bin/bash
source_string="8=FIX|35=c|79=1|80=5|31=2|80=9|31=3|44=TEST|33=1.0|9=sample|10=Test"
json_string="{8:FIX, 35:c, 79:[{80:5,31:2},{80:9}], 33:1.0, 44:TEST, 10:Test, 9:sample}"
# get the count of uniq keys on source_string in file "source_key_count"
grep -oP '[^\W]+(?==)' <<<"$source_string" | sort | uniq -c > source_key_count
# get the count of uniq keys on json_string in file "json_key_count"
grep -oP '(?<=[ ,{])[^\W]+(?=:)' <<<"$json_string" | sort | uniq -c > json_key_count
echo "== join =="
# show tabular comparation of counts: key source json
join -1 2 -2 2 source_key_count json_key_count | column -t
echo "== diff =="
# show differences between both files
diff source_key_count json_key_count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.