Search code examples
filebatch-fileecho

How to stop batch file from echoing extra line into file?


I have the following code to read how long a variable is by echoing it into a file, than reading the file length:

echo %scor% > scorfile.txt
FOR %%? IN (scorfile.txt) DO ( SET /A scorlength=%%~z? - 2 )
if %scorlength%==12 set /a scorlength=1
del /Q scorfile.txt
echo %scorlength%
pause

It believes the variable is an extra character long, and when I open scorfile.txt, there is an extra line, and I believe this is what is causing the problem. How do I fix this? Thanks!


Solution

  • I believe this is what you're looking for:

    echo | set /p="%scor%" > scorfile.txt
    FOR %%? IN (scorfile.txt) DO ( SET /A scorlength=%%~z? )
    if %scorlength%==12 set /a scorlength=1
    del /Q scorfile.txt
    echo %scorlength%
    pause
    

    The first and second lines are modified. The first modification removes the newline from the output, and the second modification strips the - 2 part of the equation you had, since I assumed you were originally using it in hopes of trying to compensate for the newline character count issue.

    Hope this solves your problem!