[英]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.