You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Grep正则匹配:查找threatLevel后7-10范围内的数字

问题:匹配JSON文件中threatLevel为7-10的条目

我有一个results.json文件,简化后内容如下:

{
          "policyId" : "pol1",
          "policyName" : "Security-High",
          "threatLevel" : 7,
          "policyViolationId" : "high",
},
{
          "policyId" : "pol2",
          "policyName" : "Security-Low",
          "threatLevel" : 1,
          "policyViolationId" : "low",
},
{
          "policyId" : "pol3",
          "policyName" : "Security-High",
          "threatLevel" : 10,
          "policyViolationId" : "high",
}

需求是扫描该文件,当发现"threatLevel" :后跟随7、8、9或10时进行报告,但用Grep正则实现范围匹配时遇到了问题,以下是我的尝试:

可行但写法繁琐

if grep -q "threatLevel\" : 7\|threatLevel\" : 8\|threatLevel\" : 9\|threatLevel\" : 10" "$FILE"; then
    echo 'threshold string does exist';
else   
    echo 'threshold string does not exist';
fi

输出:threshold string does exist

可行但不想使用elif(非不同场景)

if grep -q "threatLevel\" : [7-9]" "$FILE"; then
    echo 'threshold string does exist';
elif grep -q "threatLevel\" : 10" "$FILE"; then
    echo 'threshold string does exist';
else   
    echo 'string does not exist for regex 7-10';
fi

输出:threshold string does exist

无法生效的写法及原因

if grep -q "threatLevel\" : ([7-9]|10)" "$FILE"; then
    echo 'threshold string does exist';
else   
    echo 'threshold string does not exist';
fi

输出:threshold string does not exist

失败原因

  1. 正则语法支持问题:Grep默认使用基础正则表达式(BRE),此时()和|会被当作普通字符处理,无法实现分组或分支匹配逻辑。
  2. 缺少扩展正则开关:想要让()和|发挥正则语法作用,需要添加-E参数启用扩展正则表达式(ERE)。

修正后的写法

启用扩展正则即可正常匹配:

if grep -qE "threatLevel\" : ([7-9]|10)" "$FILE"; then
    echo 'threshold string does exist';
else   
    echo 'threshold string does not exist';
fi

或者在基础正则中转义特殊字符:

if grep -q "threatLevel\" : \( [7-9]\|10\)" "$FILE"; then
    echo 'threshold string does exist';
else   
    echo 'threshold string does not exist';
fi

更可靠的替代方案:用JSON工具处理

Grep是文本匹配工具,处理JSON这类结构化数据容易受格式变化(如空格、键顺序)影响,推荐用jq这类专门的JSON解析工具,匹配逻辑更准确:

if jq -e '.[] | select(.threatLevel >=7 and .threatLevel <=10)' "$FILE" >/dev/null; then
    echo 'threshold string does exist';
else   
    echo 'threshold string does not exist';
fi

内容的提问来源于stack exchange,提问作者cien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:45:33