使用jq在bash中处理JSON文件

时间:2015-03-18 00:59:23

标签: json bash jq

我有一个bash脚本

counter=0
for file in /home/ec2-user/Workspace/events_parts/*
do
        counter=$[counter + 1]
        event=$(cat $file | jq '.Event')
        echo $event
        if [ "$event" = "Time Exceeded" ]  || [ "$event" = "Load Time" ]; then
                echo "Coming Here"
                jq ".url = \"$(jq '.Message' $file | sed 's/.*proxy=\([^&]*\).*/\1/')\"" $file 
        else
                jq ".url = null"
        fi
done
~   

在上面的bash脚本中,我尝试从JSON文件中提取Event字段,并检查两个可能的值。if [ "$event" = "Time Exceeded" ] || [ "$event" = "Load Time" ];不符合我的预期。我已经确认我所比较的价值确实存在。

1 个答案:

答案 0 :(得分:2)

检查cat $file | jq '.Event'的输出中是否有前导或尾随不需要的字符(空格,换行符...):

cat $file | jq '.Event' | hexdump -C

<强>更新

替换

[ "$event" = "Time Exceeded" ]

通过

[ "$event" = "Time Exceeded." ]

或替换为

[ "${event%.}" = "Time Exceeded" ]

或替换为

[[ "$event" =~ "Time Exceeded" ]]

匹配子字符串。 ${event%.}会追踪.