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

如何在Bash的while循环中结合sed处理XML并执行curl请求

解决方案

文件内容说明

numbers.txt 内容

<msisdn>678678678678</msisdn>

<msisdn>456456456456</msisdn>

<msisdn123123123123</msisdn>

test.xml 内容

<soapenv:Envelope xmlns:soapenv="http://5tu6.com/net/" xmlns:net="http://5tu6.com/net"><soapenv:Header/><soapenv:Body><net:querySubscriberSettingsRequest><requestId>103</requestId><msisdn>25252623</msisdn></net:querySubscriberSettingsRequest></soapenv:Body></soapenv:Envelope>

修改后的Bash脚本

# 从test.xml提取初始requestId
start_request_id=$(grep -oP '<requestId>\K\d+' test.xml)
current_request_id=$start_request_id

# 读取numbers.txt,跳过空行
while IFS= read -r line; do
    # 跳过空行
    [[ -z "$line" ]] && continue

    # 提取有效msisdn值,兼容格式错误的行
    msisdn_value=$(echo "$line" | grep -oP '(?<=<msisdn>)\d+' | head -n1)
    if [[ -n "$msisdn_value" ]]; then
        # 生成替换后的XML内容
        temp_xml=$(sed -e "s/<requestId>[0-9]*<\/requestId>/<requestId>$current_request_id<\/requestId>/" \
                       -e "s/<msisdn>[0-9]*<\/msisdn>/<msisdn>$msisdn_value<\/msisdn>/" test.xml)

        # 执行curl发送请求,自行替换目标API地址
        echo "发送请求:requestId=$current_request_id,msisdn=$msisdn_value"
        curl -X POST -H "Content-Type: text/xml" -d "$temp_xml" "你的目标API地址"

        # requestId自增
        ((current_request_id++))
    else
        echo "跳过无效行:$line"
    fi
done < numbers.txt

关键细节说明

  • 初始requestId获取:通过grep精准提取test.xml中已有的requestId数值,保证从指定起点递增
  • 空行与无效行处理:自动跳过numbers.txt中的空行,对格式错误的msisdn行直接跳过,避免无效请求
  • XML字段替换:用sed分别替换requestId和msisdn字段,生成临时请求XML
  • curl适配:需根据实际场景调整请求方法、头部参数及目标API地址

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:05:16