joao
joao

Reputation: 61

Setting a string value to a variable

I need to set a variable to a substring I get from a find command, but it is returning the command

findstr /is "CouId:" C:\dev\AssayInfo.txt
set number=findstr /is "CouId:" C:\dev\AssayInfo.txt
echo %number% 
pause

This is what the file that I'm using findstr looks like:

Protocol: NVD_RCP_Fluidic_Accuracy_v0.4
ProtocolVersion: 1
SampleId: FLQC+20191126+00111280+96
InstrumentId: 123456789001
CouId: 138527011
CouSlot: 1

The variable should have the value 138527011 in this case.

Upvotes: 0

Views: 83

Answers (2)

double-beep
double-beep

Reputation: 5518

Personally, I would use:

@echo off

for /F "tokens=2" %%A IN ('findstr /ibc:"CouId: " C:\dev\AssayInfo.txt') do set "num=%%A"

rem Do some code here:

pause
exit /b 0

which is much shorter.

Note that direct comparisons can be done directly inside the for loop like:

@echo off
setlocal EnableDelayedExpansion

for /F "tokens=2" %%A IN ('findstr /ibc:"CouId: " C:\dev\AssayInfo.txt') do (
    set "num=%%A"
    rem Do sum comparisons with '!num!', not '%num%'!:
)
pause
exit /b %errorlevel%

Upvotes: 0

user7818749
user7818749

Reputation:

Here you go:

@echo off
for /f "tokens=1,* delims=: " %%i in ('type "C:\dev\AssayInfo.txt" ^| findstr /i CouID') do set "number=%%j"
echo %number%
:# Here you can add your if statements etc.
pause

Note, that this is exactly what you required, as per this question and not the other question and therefore this is all I can give you now.

However, this is not even needed, you can do it without the set variable:

@echo off
for /f "tokens=1,* delims=: " %%i in ('type "C:\dev\AssayInfo.txt" ^| findstr /i CouID') do (
   echo %%i
   :# Here you can add your if statements etc.
)
pause

Upvotes: 2

Related Questions