I need to extract a line from the text with batch for ngrok link

Viewed 71

I need to generate a ngrok link and show only the link with batch.

I have downloaded the web "localhost/4040/api/tunnels". I think of getting the page source. But I got this:

{"tunnels":[{"name":"command_line","ID":"7769cea7b2843d7ded705c62afde8dd3","uri":"/api/tunnels/command_line","public_url":"https://32a6-203-89-122-249.ap.ngrok.io","proto":"https","config":{"addr":"http://localhost:4040","inspect":true},"metrics":{"conns":{"count":0,"gauge":0,"rate1":0,"rate5":0,"rate15":0,"p50":0,"p90":0,"p95":0,"p99":0},"http":{"count":0,"rate1":0,"rate5":0,"rate15":0,"p50":0,"p90":0,"p95":0,"p99":0}}}],"uri":"/api/tunnels"}

Now I need to extract the public_url and the link. What can I do to extract it? The link can be different.

1 Answers
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "line={"tunnels":[{"name":"command_line","ID":"7769cea7b2843d7ded705c62afde8dd3","uri":"/api/tunnels/command_line","public_url":"https://32a6-203-89-122-249.ap.ngrok.io","proto":"https","config":{"addr":"http://localhost:4040","inspect":true},"metrics":{"conns":{"count":0,"gauge":0,"rate1":0,"rate5":0,"rate15":0,"p50":0,"p90":0,"p95":0,"p99":0},"http":{"count":0,"rate1":0,"rate5":0,"rate15":0,"p50":0,"p90":0,"p95":0,"p99":0}}}],"uri":"/api/tunnels"}"
SET "line=%line:[=%"
SET "line=%line:{=%"
SET "line=%line:]=%"
SET "line=%line:}=%"
SET "line=%line:":"=","%"
SET "line=%line:":=",%"
SET "public_url=undefined"
SET "assign_next="
FOR %%e IN (%line%) DO (
 ECHO %%e
 IF DEFINED assign_next SET "!assign_next!=%%~e"
 IF DEFINED %%~e (SET "assign_next=%%~e") ELSE (SET "assign_next=")
)
ECHO ------------------------
SET public_url
GOTO :EOF

No idea where the data line you've used as an example is stored, so I've assumed it's in an environment variable line.

As for what you mean by the link - you could have specified which field you mean, or perhaps you mean the link specified as the data item public_url.

So - assuming your data is in line, use string-replace to delete {, [, etc. by replacing by nothing, then each ":" by "," and follow the bouncing ball...

Set the name(s) of the field(s) required to undefined (just a meaningful string, nothing magic) and process line with a simple for loop as a sequence of possibly-quoted tokens separated by commas.

The echo %%e command is simply for show to allow the token being evaluated to be seen.

assign_next is "set" to nothing before the for loop, so it will start as not defined

If a token matches a defined variable, then the next token contains the desired data, so set assign_next to the name of the variable to which to assign the next token.

If assign_next is defined, then assign the current token to the variablename contained in assign_next.

... and display results using set.

Related