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

从文件提取的变量与固定变量数值比较失效问题求助

问题分析与解决

核心问题1:变量赋值语法错误

你当前的price= cat temp.html | ...写法完全错误——Shell会把price=当作临时环境变量传递给cat命令,根本没有将命令输出赋值给price变量。这直接导致第一个price变量为空值或无效内容,自然无法完成正常的数值比较。

核心问题2:提取的价格可能包含多余字符

就算赋值语法正确,从HTML文件中提取的内容大概率带有换行、空格或其他非数字字符,而-gt是整数比较运算符,只要变量中存在非数字内容,比较逻辑就会失效。

修正后的代码

# 用$()实现命令替换,完成正确赋值
price=$(cat temp.html | sed 's/,/\n/g' | grep -m 1 "selling_price" | sed 's/:/\n/g' | tail -n1)
# 清理price变量:移除所有空白字符,只保留数字
price=$(echo "$price" | tr -d '[:space:]' | sed 's/[^0-9]//g')
target=15

echo "清理后的价格:$price"
if [[ "$price" -gt "$target" ]]; then
    echo "$url"
    exit
fi

# 保留你的测试代码
price=16
target=15
echo "$price"
if [[ "$price" -gt "$target" ]]; then
    echo "$url"
    exit
fi

额外优化建议

  • 可以将提取与清理逻辑合并为一条命令,减少管道使用:
    price=$(grep -m 1 "selling_price" temp.html | sed -e 's/,/\n/g' -e 's/:/\n/g' | tail -n1 | tr -d '[:space:]' | sed 's/[^0-9]//g')
    
  • 如果涉及小数价格(如16.99),-gt无法处理,需用bc工具做浮点比较:
    if (( $(echo "$price > $target" | bc -l) )); then
        echo "$url"
        exit
    fi
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:10:18