使用批处理从 curl 的单行文本文件中提取URL

qxsslcnc  于 2022-11-13  发布在  其他
关注(0)|答案(3)|浏览(282)

我是新的批处理文件,我需要帮助提取一个URL从单行txt文件使用批处理。
下面是curl命令:

curl -X "GET" %runone% -H "accept: application/json" -o runone.txt

存储在文件(runone.txt)中的输出是一行,如下所示:

{"meta":{"terms-and-conditions":{"href":"https://apps.censored.int/datasets/licences/general/"},"license":"CC-BY-4.0","copyright":"censored"},"data":{"link":{"href":"https://apps.censored.int/webapps/opencharts/content/20220620211737-879c62d3db4f29947daaf8140a3f9261a35e4c5b.png","type":"image/png"},"attributes":{"description":"","name":"opencharts","title":"Chart"},"type":"graphical_product"},"tracker":"tracker-dd80b7a5299e46ef8aa8de4041b12aeb","uid":""}

我只想从runone.txt中选择png-file的URL(在本例中:https://apps.censored.int/webapps/opencharts/content/20220620211737-879c62d3db4f29947daaf8140a3f9261a35e4c5b.png),并将其批量存储到变量中。
谢谢你的帮助。

1cosmwyk

1cosmwyk1#

@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q72693254.txt"

SET "pngurl="&FOR /f "usebackqtokens=11,*delims={:}" %%b IN ("%filename1%") DO FOR %%e IN (%%c) DO IF NOT DEFINED pngurl SET "pngurl=%%~e"

ECHO pngurl=%pngurl%
GOTO :EOF

请注意,如果文件名不包含分隔符(如空格),则%filename1%不需要用引号引起来,因此可以省略usebackq
解决方案取决于所描述的输出文件格式。

b4qexyjb

b4qexyjb2#

您可以尝试使用Powershell和Batch解析JSON文件并从中提取一个链接,如下所示:

@echo off
Title Parse JSON File And Exctract A Link From It Using Powershell And Batch
Set "JSON_File=%~dp0runone.txt"
set psCmd="&{(GC "%JSON_File%" | ConvertFrom-Json).data.link.href}"
Call :RunPS %psCmd% URL
Echo "%URL%"
pause & Exit
::-------------------------------------------------------------------
:RunPS <PassPSCMD> <RetValue>
@for /F "usebackq tokens=*" %%i in (`Powershell %1`) do set "%2=%%i"
Goto:eof
:: End of :RunPS function
::-------------------------------------------------------------------
xpcnnkqh

xpcnnkqh3#

由于输出是JSON,我建议您看一看JSON解析器xidel。它将为您省去很多麻烦和头痛,特别是因为Batch的局限性。

xidel -s --method=GET -H "accept: application/json" "%runone%" -e "$json/data/link/href"

这将打开url并从JSON中提取png文件的url。由于xidel可以打开url,因此不需要curl,也不需要将JSON保存到文件中。
“GET”是默认的方法,所以你可以不使用--method=GET,也可以不使用header。
要将png-file-url分配给变量,请执行以下操作:

FOR /F "delims=" %A IN ('
  xidel -s --method=GET -H "accept: application/json" "%runone%" -e "$json/data/link/href"
') DO SET "pngurl=%A"

或者可替换地:

FOR /F "delims=" %A IN ('
  xidel -s --method=GET -H "accept: application/json" "%runone%" -e "pngurl:=$json/data/link/href" --output-format^=cmd
') DO %A
  • (如果要在批处理文件中使用此命令,请使用%%A而不是%A)*

相关问题