简体   繁体   中英

Count For loop with number at start of each line

I have been trying to figure how to count the number of loops and display this number at the beginning of the loop.

:Search
set location=%cd%
cls
echo.
Echo. Searching for .exe files in %location% and subfolders
echo.
set /a count=0
echo.___________________________________________
echo.Found:
echo.
FOR /r %%i in (*.exe) do (echo. %count%. %%~ni & set /a count+=1)
echo.___________________________________________
echo.
title Exe blocker %count% Files found
echo. Number of files found with .exe extention: %count%
echo.
echo.

The above code searches for exe files in a folder (and sub folders). I want the code to display:

1. Firstexefilename
2. Secondexefilename

But it displays

0. FirstexefileName
0. SecondexefileName

The final count variable works fine displaying 2.

Next code snippet shows some chances of solution with delayed expansion: enabled (expand variables at execution time rather than at parse time) or disabled (expand variables at parse time rather than at execution time, this is the default behaviour ):

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
:Search
set "location=%cd%"
cls
echo(
echo( Searching for .exe files in %location% and subfolders
echo(
set /a count=0
echo(___________________________________________
echo(Found:
echo(
FOR /r %%i in (*.exe) do (echo( !count!. %%~ni & set /a count+=1)
echo(___________________________________________
echo(
title Exe blocker %count% Files found
echo( Number of files found with .exe extention: %count%
echo(
echo(
ENDLOCAL

echo( Another approach using `findstr.exe` and delayed expansion disabled:
echo(
SETLOCAL EnableExtensions DisableDelayedExpansion
FOR /F "tokens=1,* delims=:" %%i in ('
  dir /B /S *.exe^|findstr /N "^"
  ') do (echo( %%i. %%~nj & set /a "counter=%%i")
echo(___________________________________________
echo(
echo( Number of files found with .exe extention: %counter%
ENDLOCAL

Yet another approach corresponding to your original solution:

SETLOCAL EnableExtensions
:Search
set "location=%cd%"
rem cls
echo(
echo( Searching for .exe files in %location% and subfolders
echo(
set /a count=0
echo(___________________________________________
echo(Found:
echo(
FOR /r %%i in (*.exe) do (
  set "_filename=%%~ni"
  call :usevariable
  set /a "count+=1"
)
echo(___________________________________________
echo(
title Exe blocker %count% Files found
echo( Number of files found with .exe extention: %count%
echo(
echo(
ENDLOCAL
goto :eof

:usevariable
echo( %count%. %_filename%
goto :eof

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM