繁体   English   中英

XP中的一系列管道后,批处理文件停止

[英]Batch file stops after a series of pipes in XP

我有一个以下批处理文件,该文件从JSON格式的数据库中检索数据,提取数字并存储它们:

set server=http://login:password@host:port
set db=PostgreSQL%%20DB

del IDs.txt
echo Section1 >> IDs.txt
curl "%server%/%db%/Section1" | jq .[] | jq .[] >> IDs.txt
echo Section2 >> IDs.txt
curl "%server%/%db%/Section2" | jq .[] | jq .[] >> IDs.txt
echo Section3 >> IDs.txt
curl "%server%/%db%/Section3" | jq .[] | jq .[] >> IDs.txt
...

它在Windows 8下工作,但在Windows XP下,它在第一行curl-jq行之后停止。 没有错误。 检索号码可以正常工作,但只能一次。

我尝试将curl-jq调用替换为

cmd /c "curl %server%/%db%/Section3 | jq .[] | jq .[] >> IDs.txt"

但这没有帮助。

怎么了? 有没有办法使它在XP中工作?

提前致谢。

更新:这是输出JSON的示例:

{"ids":[80001]}

要么

{"ids":[12001,12002,12003,43120]}

我需要的只是将数字提取为一列:

80001

要么

12001
12002
12003
43120

也许这可以帮助您?

@echo off

for /F "tokens=2 delims=[]" %%a in (input.txt) do (
   for %%b in (%%a) do (
      echo %%b
   )
)

输出示例:

C:\> type input.txt
{"ids":[80001]}

C:\> test.bat
80001

C:\> type input.txt
{"ids":[12001,12002,12003,43120]}

C:\> test.bat
12001
12002
12003
43120

与其尝试使用两个jq调用,不如使用一个。 此外,通常最好在命令行中给jq过滤器加引号。

您正在转储ids属性中的值,因此:

jq ".ids[]"

[编辑:在Windows和许多其他平台上都可以使用双引号,但是在非Windows平台上,单引号通常是最好的选择。]

尝试此脚本,看看它是否满足您的要求。 它不使用cURL来获取JSON,而是使用XMLHTTPRequest。 与其依赖jq来反序列化JSON,它使用JavaScript JSON解析器。 而且与Aacini的解决方案不同,无论JSON是否缩小,美化等等,它的工作原理都相同。 用.bat扩展名保存。

@if (@CodeSection == @Batch) @then
@echo off & setlocal

set "server=http://login:password@host:port"
set "db=PostgreSQL DB"

>IDs.txt cscript /nologo /e:Jscript "%~f0" "%server%" "%db%"

goto :EOF
@end // end Batch / begin JScript hybrid chimera

var XHR = WSH.CreateObject('Microsoft.XMLHTTP'),
    htmlfile = WSH.CreateObject('htmlfile'),
    args = { 'server': WSH.Arguments(0), 'db': WSH.Arguments(1) },
    url = encodeURI(args.server + '/' + args.db + '/Section'),
    section = 0;

function fetch(url) {
    XHR.open('GET', url, true);
    XHR.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
    XHR.send('');
    while (XHR.readyState != 4) { WSH.Sleep(50); }
    return XHR.status == 200 ? XHR.responseText : '';
}

// import JSON method from htmlfile COM object
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
var JSON = htmlfile.parentWindow.JSON;

// fetch JSON by section sequentially until 404 error
while ((response = fetch(url + ++section))) {
    WSH.Echo('Section' + section);
    ids = JSON.parse(response).ids;
    for (var i in ids) WSH.Echo(ids[i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM