使用 xargs 参数化批量调用 curl 命令

短、平、快。

背景

有时,需要批量处理一个文件里的多条数据。

比如,有一个文件 file.txt ,含有一系列店铺ID。 有个现成的命令 curl_search 可以处理文件里的单个店铺。那么,如何批量处理数据呢 ?

file.txt

111,222,333

curl_search:

curl -s -H "Content-Type: application/json" -X POST -d '{"source":"xxx", "orderBy":"createTime", "order":"desc", "requestId":"111", "searchParam": {"shopId": 111, "endTime":1583424000,"startTime":1580486400}}' http://127.0.0.1:7001/app/order/search

curl_search 的结果是:

{"result":true,"code":0,"message":null,"data":{"success":true,"code":200,"message":"successful","requestId":null,"errorData":null,"data":{"orderNos":["E001","E002'],"total":22}}}

想拿到的结果是:每行一个 kdtId total

111 22
222 256
333 1024


解决方案

先定义一个 脚本:

curl_m.sh

#!/bin/sh

shopId=$1

curl -s -H "Content-Type: application/json" -X POST -d  '{"source":"xxx", "orderBy":"createTime", "order":"desc", "requestId":"'"${shopId}"'", "searchParam": {"shopId":"'"${shopId}"'", "endTime":1583424000,"startTime":1580486400}}' http://127.0.0.1:7001/trade-manage/order/searchOrderNos | echo $kdtId $(sed -r 's/^.*total.*:([0-9]+)\}.*$/\1/')

然后使用 :

cat /tmp/file.txt | tr "," "\n" | xargs -I {} sh curl_m.sh {}  > final_orders.txt


求解过程

这里有两个问题要解决:1. 从 curl_search 命令的结果中解析出 total ; 2. 批量调用 curl 命令,必须把 shopId 作为参数传进去。

解析total

解析 total , 使用 sed + 正则捕获能力。 正则表达式基础见: "正则表达式基础知识"

策略是,将 需要的东西 用 ( ) 括起来,然后用引用替换。比如,我只要 total 冒号后面的 数字, 就将需要的部分 :([0-9]+)\} 识别出来并括起来 ,然后使用引用符号 $n 拿到。

参数化调用curl

需要把 shopId 传到 curl 命令中。 但是 curl 命令中既有 双引号,也有单引号,这些都会使得变量引用失效。 可以使用 "'${shopId}'" 来传入 shopId。

命令替换

$(command) : 用的 command 的计算值来替换 command 本身,从而能将 command 的计算值作为参数传给其它命令。


重定向

> 是重定向符号,可以将命令执行结果重定向到文件里。当命令结果非常大时适用。


猜你喜欢

转载自www.cnblogs.com/lovesqcc/p/12431063.html
今日推荐