使用 xargs 参数化批量调用 curl 命令
短、平、快。
背景
产品同学给了一个店铺 shopId 列表,想要知道这些店铺的最近一段时间的同城送订单的数量。
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, "deliveryType":"local_delivery"}}' http://127.0.0.1:7001/app/order/search
curl_search 的结果如下。 total 即是同城送订单的数量。
{"success":true,"code":200,"message":"successful","data":{"orderNos":["E001","E002"],"total":22}}
想拿到的结果是:每行一个 shopId total
111 22
222 256
333 1024
解决方案
先定义一个 脚本 curl_orders.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/app/order/search | echo $shopId $(sed -r 's/^.*total.*:([0-9]+)\}.*$/\1/')
然后使用 :
cat /tmp/file.txt | tr "," "\n" | xargs -I {} sh curl_orders.sh {} > result.txt
求解过程
方案选择
最先想到用 python 来解决。但是 python 解决要拼参数,写调用 curl 的脚本。有点麻烦。 接着想去数据平台用 hive 捞,但是没有同城送订单的标识。想到既然有 curl 命令可以拿到单个店铺的结果,只要解决批量的问题即可。
这里有两个问题要解决:1. 从 curl_search 命令的结果中解析出 total ; 2. 批量调用 curl 命令,必须把 shopId 作为参数传进去。
解析total
解析 total , 使用 sed + 正则捕获能力。
要领是:将 需要的东西 用 ( ) 括起来,然后用引用替换。比如,我只要 total 冒号后面的 数字, 首先将需要的部分 ([0-9]+)
括起来 ,然后使用 左边 "total".*:
和 右边 \}
进行识别, 最后通过引用符号 $1 拿到。数字标识第几个(被捕获的分组)括号。
正则表达式基础见: "正则表达式基础知识"
参数化调用curl
需要把 shopId 传到 curl 命令中。 但是 curl 命令的选项 -d 的参数 ‘{"shopId":"xxx", "field2":"yyy"}‘,既有 双引号也有单引号,这些都会使得变量引用 $param 变成普通的字符串,而不是被替换成指定的值。 可以使用 "‘${shopId}‘" 来传入 shopId。
xargs
xargs 可以读取文件并将每一行数据作为参数传给指定的命令执行。 基本形式是: cat file.txt | xargs -I {} Command {} 。 {} 就是 file.txt 里的每一行数据。
这里之所以将调用 curl 并解析出 total 写成一个 curl_orders.sh 脚本文件,也是为了 xargs 命令更加简洁。
命令替换
$(command) : 用的 command 的计算值来替换 command 本身,从而能将 command 的计算值作为参数传给其它命令。
重定向
> 是重定向符号,可以将命令执行结果重定向到文件里。当命令结果非常大时适用。
原文:https://www.cnblogs.com/lovesqcc/p/12431063.html