Windows cmd: echo without newline but with CR

I would like to write on one line inside a loop in a windows batch file. For example:

setlocal EnableDelayedExpansion
set file_number=0
for %%f in (*) do (
  set /a file_number+=1
  echo working on file number !file_number!
  something.exe %%f
)
setlocal DisableDelayedExpansion

      

This will lead to:

echo is working on file number 1

echo is working on file number 2

echo is working on file number 3

.,.

I would like them all to be on the same line. I found a hack for a newline (for example, here: windows package: echo without newline ), but this will produce one long line.

Thank!

+3


source to share


2 answers


@echo off
    setlocal enableextensions enabledelayedexpansion

    for /f %%a in ('copy "%~f0" nul /z') do set "CR=%%a"

    set "count=0"
    for %%a in (*) do (
        set /a "count+=1"
        <nul set /p ".=working on file !count! !CR!"
    )

      

The first command for

performs a copy operation that leaves a carriage return inside the variable.

Now, in the file loop, each line will echo using <nul set /p

which will output the prompt line without the line and don't wait for input (we're reading from nul

). But inside the echo data, we include the carriage return previously received.



BUT for it to work, the variable CR

must be discarded with an expansion delay. Otherwise it won't work.

If for some reason you need to disable slow expansion, you can do so without the CR variable using the for

swap parameter

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f %%a in ('copy "%~f0" nul /z') do (
        for /l %%b in (0 1 1000) do (
            <nul set /p ".=This is the line %%b%%a"
        )
    )

      

+7


source


Thanks to MC ND's answer , I have a subroutine echocr

that you can call without delayed expansion that will echo a line with a carriage return and there is no newline. (Spaces after are %input%

configured to cover all previous messages).

You can use it to rewrite a string as shown in the modified code:



@echo off

call :echocr "good morning"
PING -n 2 127.0.0.1>nul
call :echocr "good afternoon"
PING -n 2 127.0.0.1>nul
call :echocr "bye now"
PING -n 2 127.0.0.1>nul
pause

:echocr

:: (echo string with carriage return, no line feed)

for /F "tokens=1 delims=# " %%a in (
'"prompt #$H# & echo on & for %%b in (1) do rem"'
) do set "backspace=%%a"

set input=%~1
set "spaces40=                                       "
set "spaces120=%spaces40%%spaces40%%spaces40%
for /f %%a in ('copy "%~f0" nul /z') do (  
    set /p ".=*%backspace%%spaces120%%%a" <nul      
    set /p ".=*%backspace%%input%%%a" <nul
)    
exit /b

      

+1


source







All Articles