VeeTouine
VeeTouine

Reputation: 13

How to get a path variable in a text file by using FOR in a Windows batch file?

I try to retrieve a path in a text file identified by a tag.

I have a line like that in my text file:

"mypath":"C:\myfolder"

I need to retrieve the path corresponding to mypath tag.

I tried this:

for /f tokens^=2^,3^ delims^=^"^:^" %%a in ('type %mytextfile%^|find """mypath"""') do (  
    echo %%a 
    echo %%b
)

But it doesn't work, the result is:

mypath
C

So my problem probably comes from the colon character that is used in the delimiter and in the string I want to get.

Upvotes: 1

Views: 168

Answers (1)

Joey
Joey

Reputation: 354566

Two points: First, just use quotes for the for options instead of escaping everything. Second, you can add a * after a tokens option to imply that no more tokenizing should be done and the rest should be returned as a single token:

for /f "tokens=1* delims=:" %%A in ('findstr /b /c:"""mypath""" %mytextfile%') do (
  echo %%~A
  echo %%~B
)

A few more things:

  • There's no need for type when the command you're piping to can read files just fine. :-)
  • findstr /b matches the search string at the beginning of the line, as an added check that you've really got the correct line.
  • The ~ for printing the variables just eliminates the quotes around the text, so you don't have to deal with them anymore.

Upvotes: 2

Related Questions