在批处理文件中,我想计算几个目录中文件中的行,并在该批处理中稍后使用环境变量中的行计数。例如,请考虑我有以下文件:
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 ..
)
现在我打开一个新的命令窗口并调用该批处理。第一个电话的结果是:
Processing Directory1
Count is
Processing Directory2
Count is
Processing Directory3
Count is
在同一命令窗口中的任何后续调用都会导致
Processing Directory1
Count is 3
Processing Directory2
Count is 3
Processing Directory3
Count is 3
我在这里做错了什么?
答案 0 :(得分:1)
根据@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 ..
)
答案 1 :(得分:1)
问题是 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%
额外%
s,然后在执行循环期间强制扩展 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 )。