Windows Batch SET Syntax

為{幸葍}努か 提交于 2019-12-08 09:23:32

问题


I have adopted some code from here:

Extract substring between 2 strings

Rem Looking for a test.txt substring preceded by page\[%%x\]= and succeeded by ;
@Echo Off

for /l %%x in (0, 1, 4) do (
   echo %%x
   For /F "Delims=" %%A In ('FindStr /I "page\[%%x\]=.*;" "test.txt"') Do Call :Sub "%%A" "%%x"
)

Pause
GoTo :EOF

:Sub
Set "Line=%~1"

Set "Up2Sub=%Line:*page[ %~2 ]=%"

Set "SubStr=%Up2Sub:;="&:"%"
Echo %SubStr% > test%~2.json
Exit /B

The issue I am having is regarding this line:

Set "Up2Sub=%Line:*page[ %~2 ]=%"

The variable %~2 does not get concatenated correctly.

What would be the syntax to get this value of the %~2 variable added to this SET statement in between the []?

Thanks

Sample text.txt

....

page[0]={*****};
page[1]={*****};
page[2]={*****};
page[3]={*****};
page[4]={*****};

....

回答1:


To split a string, you can also use a for /f loop:

@Echo Off
for /l %%x in (0, 1, 4) do (
   For /F "Delims=" %%A In ('FindStr /I "page\[%%x\]=.*;" "test.txt"') Do (
     for /f "tokens=2 delims=;=" %%s in ("%%A") do echo %%x: %%s
   )
)
Pause

This splits the string (%%A) into tokens, separated by ; and =. With page[0]={*****};, the first token is page[0],then =is a delimiter. The second token is {*****} and the third token (after the;) is empty. we just include the ';' to the delimters to get rid of it.

With a little analyzing your file and choosing tokens and delims right, you can even reduce the code to a single for:

For /F "tokens=2,4 delims=[]{}" %%A In ('FindStr /I "page\[[0-4]\]=.*;" "test.txt"') Do echo {%%B}>test%%A.json


来源:https://stackoverflow.com/questions/57708292/windows-batch-set-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!