gpt4 book ai didi

for-loop - CMD For 循环不保存设置/值

转载 作者:行者123 更新时间:2023-12-02 22:15:27 24 4
gpt4 key购买 nike

不知道如何解释清楚,所以这是代码

@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 次,每次 test 都会获得 +1,并且/a 显示正确的值X,但 for 循环上的最后一个 echo 显示 0,这是循环之前设置的 test。

在循环完成之前,test 的值不会改变...有什么办法可以解决这个问题吗?

这就是我想要完成的任务,因为可能有一种更简单的方法:我想运行一个 for 循环,在一系列子文件夹中查找 str 的所有 rtf,并将它们全部复制到具有新名称的 all 目录中, 1.rtf、2.rtf、3.rtf 等。我需要在传输时重命名它们的原因是它们都有相同的名称。

最佳答案

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

关于for-loop - CMD For 循环不保存设置/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/980718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com