Question

I am trying to write a simple batch command that reads the second line of a file (ProfileName), looks for a ";" in that line and then splits the line and stores it in two variables (ProfileName and RRSProfileName)

    for /F "tokens=1 skip=1" %%A in (%ContentFilePath%) do ( SET ProfileName=%%A )
    ECHO %ProfileName% | findstr /spin ";">nul
    IF %ERRORLEVEL%==0 (
         FOR /F "tokens=1,2 delims=;" %%A in ("%ProfileName%") do ( SET ProfileName=%%A& SET RRSProfileName=%%B ) 
    )

ContentFile contains 2 lines

    blah
    blah1

For some reason, ProfileName variable does not get set if the "IF" statement is present. If I remove the "IF" statement, ProfileName gets set to blah1. This is bizzare. Can someone help? Both ProfileName and RRSProfileName are set to "" initially.

Was it helpful?

Solution 2

findstr /spin

it search in subdirectories (/s) omitting non printable files (/p) ignoring case (/i) numbering output lines (/n), and you are not giving any file, so findstr fails as its arguments are not correct. From here you get errorlevel 1, so, the code inside the if is not executed

Better use

for /F "usebackq tokens=1 skip=1" %%A in ("%ContentFilePath%") do ( SET "ProfileName=%%A" )
ECHO %ProfileName%| find ";" > nul 
IF %ERRORLEVEL%==0 (
     FOR /F "tokens=1,2 delims=;" %%A in ("%ProfileName%") do ( SET "ProfileName=%%A" & SET "RRSProfileName=%%B" ) 
)

Or just (if it is possible, i don't know all your cases), join the two steps into one

for /f "usebackq tokens=1,2 skip=1 delims=;" %%a in ("%ContentFilePath%"
) do ( set "ProfileName=%%a" & set "RRSProfileName=%%b" )

It reads the same required line, if semicolon is present, it is used to split the line and each of the variables retrieve the required content.

OTHER TIPS

for /F "tokens=1,2 skip=1delims=;" %%A in (q22602116.txt) do SET "ProfileName=%%A"&SET "RRSProfileName=%%B"

worked perfectly well for me, assuming that Profilename should be set to the portion before the semicolon on the last line and RRSprofilename to the portion after (if it exists)

But - be careful of the presence of Spaces in a string-assignment - they are significant (original batch appeared to have trailing spaces...) - the quotes positioned just so should overcome this characteristic...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top