我有一個json檔案:
cat myjsonfile.json
{
"directory": true,
"condition": "",
"specialCondition": "",
"dataFiles": "",
"nonstandard-protocol": true
}
specialCondition是標準化的,可以為空或具有matchedorunmatched狀態。
我只是想把translate那些條件當成另一個狀態。nonstandard-protocolfalse
所以我在我的 bash 腳本中寫了這個。
if [[ "jq '.specialCondition' myjsonfile.json | grep -q 'matched'" && "jq '."nonstandard-protocol"' myjsonfile.json | grep -q 'false'" ]]; then echo 'MATCHED' | cat > protocol_result.txt; fi
if [[ "jq '.specialCondition' myjsonfile.json | grep -q 'unmatched'" && "jq '."nonstandard-protocol"' myjsonfile.json | grep -q 'false'" ]]; then echo 'NOTMATCHED' | cat > protocol_result.txt; fi
但是,這會回傳不正確的結果。當我運行腳本時,我總是看到它首先寫入MATCHED我的protocol_result.txt,然后在第二if行寫入NOTMATCHED檔案!雖然它根本不應該寫任何東西......為什么會這樣?
uj5u.com熱心網友回復:
將if陳述句帶到jq并讓它輸出你想要的任何東西。
以下示例""在nonstandard-protocol為 true 或specialCondition既不是matched也不列印任何內容unmatched。否則它將列印MATCHEDor NOTMATCHED,具體取決于specialCondition:
jq --raw-output '
if ."nonstandard-protocol" then ""
else if .specialCondition == "matched" then "MATCHED"
elif .specialCondition == "unmatched" then "NOTMATCHED"
else "" end
end
' myjsonfile.json > protocol_result.txt
演示
注意: Using""不會像預期的那樣列印任何內容,但后跟一個換行符,因為它有一個輸出(本質上是一個空行)。如果您不希望這樣,請更改""為empty.
uj5u.com熱心網友回復:
如果您需要它的狀態碼,您需要實際執行您的grep命令:
if jq .specialCondition myjsonfile.json | tee protocol_result.txt | grep -q matched && jq .nonstandard-protocol myjsonfile.json | tee -a protocol_result.txt | grep -q false
then
.....
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425931.html
下一篇:洗掉等號后的多行字串
