Mike
Mike

Reputation: 35

extract string from text with batch

I am working on an automation project: to complete the puzzle I left with this thing.

I have a file (com.txt):

AUX = \DosDevices\1
1 = \Device\Serial0
10 = \Device\VCP0
7 = \Device\Silabser0
8 = \Device\Silabser1

I need to read this file using batch and create 3 variables: look for "Silabser0" and insert "7" to a var look for "Silabser1" and insert "8" to a var and look for "VCP0" and insert "10" to a var (those numbers are changing from file to file but the Silabser0/1 and VCP0 are permanent )

output for npocmaka:

C:\Users\Test\Desktop>set file_loc=c:\COMports.txt

C:\Users\Test\Desktop>for /F "usebackq tokens=1 delims== " %a in ("c:\COMports.t
xt") do (for /F "tokens=2 delims=\" %x in ("%b") do set %x=%a )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=AUX )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=1 )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=10 )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=7 )

C:\Users\Test\Desktop>(for /F "tokens=2 delims=\" %x in ("%b") do set %x=8 )

C:\Users\Test\Desktop>echo
ECHO is on.

C:\Users\Test\Desktop>echo
ECHO is on.

C:\Users\Test\Desktop>echo
ECHO is on.

Upvotes: 2

Views: 453

Answers (2)

Mike
Mike

Reputation: 35

iv'e edited the file to look like:

AUX\DosDevices\1
1\Device\Serial0
10\Device\VCP0
7\Device\Silabser0
8\Device\Silabser1

and then used:

set file_loc=c:\COMports.txt

for /f "tokens=1,3 delims=\" %%a in (%file_loc%) do set %%b=%%a

Upvotes: 0

npocmaka
npocmaka

Reputation: 57332

not tested (assuming that paths always has two separators - \)

@echo off

set file_loc=vals.txt

for /f "usebackq tokens=1* delims== " %%a in ("%file_loc%") do (
   for /f "tokens=2 delims=\" %%x in ("%%b") do set %%x=%%a
)

echo %Serial0%
echo %VCP0%
echo %Silabser0%
echo %Silabser1%

Upvotes: 1

Related Questions