CMD For Loop不保存set / a值 [英] CMD For Loop does not hold set /a value

查看:288
本文介绍了CMD For Loop不保存set / a值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道如何解释这一点,所以这里是代码

Didn't know how to explain this well, so here is the code

@echo off
set test=0

for /f %%a in (textfile.txt) do (
rem loops five times(5 lines in textfile.txt)

set /a test=test+1
rem Adds 1 to Test

echo %%a
rem Echo's correct line in file

echo %test%
rem Echo's whatever X was before the loop

)

echo %test%
rem Displays the correct value of X

pause

这只是我发现问题的一个例子,txtfile.txt有5线,所以for循环5次,每次,测试得到+1,并且/ a显示正确的X值,但是for循环的最后一个回显示0,这是测试设置之前

this is just an example of where I am finding the problem, txtfile.txt has 5 lines, so the for loop goes 5 times, each time, test gets +1 to it, and the /a displays the correct value of X, but the last echo on the for loop displays 0, which is what test is set to before the loop.

测试的值不会改变,直到循环完成...有任何方法来解决这个问题吗?

The value of test is not changing until the loop is finished... is there any way to fix this?

这里是我想要完成的,因为可能有一个更简单的方法:我想运行一个for循环findstr的所有rtf的一系列子文件夹,并将其全部复制到一个所有目录与新名称,1.rtf,2.rtf,3.rtf等。我需要在传输上重命名它们的原因是它们都有相同的名称。

Here is what I want to accomplish, as there may be an easier way: I want to run a for loop that findstr's all rtf's in a series of sub folders, and copies them all to a all directory with a new name, 1.rtf,2.rtf,3.rtf, etc. The reason I need to rename them on the transfer is they all have the same name.

推荐答案

Lucero 是对的。

示例代码:

@echo off
setlocal enabledelayedexpansion
echo.
set numLines=0
echo examining file '%~f0'
echo.
rem loop N times, once for each line in the file
for /f %%a in (%~f0) do (

    rem add 1 to the numLines variable
    set /a numLines=!numLines!+1

    rem echo the first symbol from the line 
    echo line !numLines!: %%a
)

rem Display the number of lines in the file
echo.
echo The file '%~f0' has %numLines% lines.
echo.

pause
echo.
endlocal

这篇关于CMD For Loop不保存set / a值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆