Page 1 of 1

How to return a string position?

Posted: 28 Feb 2012 23:09
by tinfanide
test.txt
[UserData]
FullName = "Your User Name"
OrgName = "Your Organization Name"
ComputerName = *
ProductKey= "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"


How could I return a specific string position in a text file?
I know there's string manipulation commands (e.g. Left, Mid...)
But I want to search for a string and return its position.

Thanks in advance.

Re: How to return a string position?

Posted: 29 Feb 2012 02:43
by foxidrive
Tell us exactly what you want to do and you will get an appropriate answer.

Re: How to return a string position?

Posted: 29 Feb 2012 04:11
by tinfanide

Code: Select all

@ECHO OFF

FOR /F "tokens=*" %%C IN (test.txt) DO (
SETLOCAL ENABLEDELAYEDEXPANSION

SET "old=%%C"

:: ProductKey= (the equal sign "=" is not escaped)

SET new=!old:ProductKey==!
IF DEFINED new (
:: ECHO) = ECHO.
   ECHO.!new!
)
ENDLOCAL
)

PAUSE


Originally I wanted to extract the product key.
I thought of finding the exact position to extract the key but I was also thinking of using the string substitution method.
But I'm stuck at how to escape the equal sign.

Re: How to return a string position?

Posted: 29 Feb 2012 04:21
by foxidrive
Try this:

Code: Select all

@echo off
for /f "tokens=2 delims==" %%a in ('type "test.txt" ^|find "ProductKey="') do set PK=%%a
echo %PK%

Re: How to return a string position?

Posted: 02 Mar 2012 10:35
by tinfanide
foxidrive wrote:Try this:

Code: Select all

@echo off
for /f "tokens=2 delims==" %%a in ('type "test.txt" ^|find "ProductKey="') do set PK=%%a
echo %PK%


Yes, this works. Thanks.