I'm new in batch files and I need help extracting an URL from a single-line txt-file using Batch.
This is the curl command:
curl -X "GET" %runone% -H "accept: application/json" -o runone.txt
The output stored in the file (runone.txt) is a single line like this:
{"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":""}
I only want to pick the URL to the png-file from the runone.txt (in this example: https://apps.censored.int/webapps/opencharts/content/20220620211737-879c62d3db4f29947daaf8140a3f9261a35e4c5b.png) and store it to a variable in batch.
Thanks for your help.
CodePudding user response:
You can try to parse the JSON File and exctract a link from it using Powershell and Batch like this code below :
@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
::-------------------------------------------------------------------
CodePudding user response:
@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
Note that if the filename does not contain separators like spaces, then %filename1%
does not need to be quoted, and then the usebackq
can be omitted.
Solution depends on the format of the output file being as described.