Count For循环,每行开头有数字

时间:2015-11-27 23:27:04

标签: batch-file for-loop counter

我一直试图计算如何计算循环次数并在循环开始时显示此数字。

: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.

以上代码搜索文件夹(和子文件夹)中的exe个文件。我希望代码显示:

1. Firstexefilename
2. Secondexefilename

但它显示

0. FirstexefileName
0. SecondexefileName

最终计数变量正常显示2。

1 个答案:

答案 0 :(得分:0)

下一个代码段显示了延迟扩展解决方案的一些机会:enabled(在执行时而不是在解析时扩展变量)或禁用(在解析时扩展变量而不是在执行时间,这是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

另一种与原始解决方案相对应的方法:

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