批量计算子目录中文件中的行会给出错误的结果
Batch to count lines in files in subdirectories gives wrong results
在一个批处理文件中,我想计算几个目录中文件的行数,并在稍后的批处理中使用环境变量中的行数。例如,假设我有以下文件:
Directory1\update.log (1 line)
Directory2\update.log (2 lines)
Directory3\update.log (3 lines)
这是我正在使用的批处理文件:
for /d %%d in (*.*) do (
echo Processing %%d
cd %%d
for /f %%c in ('find /v /c "" ^< update.log') do set count=%%c
echo Count is %count%
cd ..
)
现在我打开一个新命令 window 并调用该批处理。第一次调用的结果是:
Processing Directory1
Count is
Processing Directory2
Count is
Processing Directory3
Count is
并且同一命令中的任何后续调用 window 都会导致
Processing Directory1
Count is 3
Processing Directory2
Count is 3
Processing Directory3
Count is 3
我做错了什么?
根据@RyanBemrose 的评论,我发现 this question 引导我使用以下工作代码:
setlocal ENABLEDELAYEDEXPANSION
for /d %%d in (*.*) do (
echo Processing %%d
cd %%d
for /f %%c in ('find /v /c "" ^< update.log') do set count=%%c
echo Count is !count!
cd ..
)
问题是 cmd 在读取循环 时扩展了 %count%
。这导致 cmd 执行以下循环:
echo Processing %d
cd %d
for /f %c in ('find /v /c "" ^< update.log') do set count=%c
echo Count is
cd ..
如果您不喜欢延迟扩展,另一个技巧是用额外的 %
引用 %count%
,然后在循环执行期间强制扩展 会 call
.
for /d %%d in (*.*) do (
echo Processing %%d
cd %%d
for /f %%c in ('find /v /c "" ^< update.log') do set count=%%c
call echo Count is %%count%%
cd ..
)
呃(一般来说 cmd)。
在一个批处理文件中,我想计算几个目录中文件的行数,并在稍后的批处理中使用环境变量中的行数。例如,假设我有以下文件:
Directory1\update.log (1 line)
Directory2\update.log (2 lines)
Directory3\update.log (3 lines)
这是我正在使用的批处理文件:
for /d %%d in (*.*) do (
echo Processing %%d
cd %%d
for /f %%c in ('find /v /c "" ^< update.log') do set count=%%c
echo Count is %count%
cd ..
)
现在我打开一个新命令 window 并调用该批处理。第一次调用的结果是:
Processing Directory1
Count is
Processing Directory2
Count is
Processing Directory3
Count is
并且同一命令中的任何后续调用 window 都会导致
Processing Directory1
Count is 3
Processing Directory2
Count is 3
Processing Directory3
Count is 3
我做错了什么?
根据@RyanBemrose 的评论,我发现 this question 引导我使用以下工作代码:
setlocal ENABLEDELAYEDEXPANSION
for /d %%d in (*.*) do (
echo Processing %%d
cd %%d
for /f %%c in ('find /v /c "" ^< update.log') do set count=%%c
echo Count is !count!
cd ..
)
问题是 cmd 在读取循环 时扩展了 %count%
。这导致 cmd 执行以下循环:
echo Processing %d
cd %d
for /f %c in ('find /v /c "" ^< update.log') do set count=%c
echo Count is
cd ..
如果您不喜欢延迟扩展,另一个技巧是用额外的 %
引用 %count%
,然后在循环执行期间强制扩展 会 call
.
for /d %%d in (*.*) do (
echo Processing %%d
cd %%d
for /f %%c in ('find /v /c "" ^< update.log') do set count=%%c
call echo Count is %%count%%
cd ..
)
呃(一般来说 cmd)。