停批文件只处理最后一个文件? [英] Stop batch file only processing last file?
问题描述
我重命名* .txt文件并删除第一个X字符以下简单的批处理文件
I have the following simple batch file for renaming *.txt files and removing the first x characters
@Echo Off
for %%i in ("*.txt") do (
set fname=%%i
echo %fname%
copy %fname% %fname:~9%
)
然而,这只是处理的最后一个文件?如果我在那里有4个文件,最后一个文件被复制4倍呢?
However, it only processes the last file? If I have 4 files in there, the last file gets copied 4 times as well?
我需要做什么呢?
推荐答案
的问题是,%变种%是由变量的值替换当回路第一次被解析,并在执行过程中不改变。
The problem is that %var% is replaced by the variable's value when the loop is first parsed, and doesn't change during execution.
下面是一个示范,应允许您解决您的code:
Here's a demonstration which should allow you to fix your code:
@ECHO off&setlocal&CLS
ECHO Demonstrating the use of %%var%% IN a block
ECHO.
SET var=Original value
ECHO Before the block, %%var%%=%var%
FOR %%i IN (1 2 3) DO (
SET var=New value %%i
ECHO loop %%i : %%var%%=%var%
)
ECHO After the block, %%var%%=%var%
ECHO.
ECHO BECAUSE the block is first PARSED, then executed.
ECHO in the parsing process, %%var%% is replaced by its
ECHO value as it stood when the block was parsed - BEFORE execution
ECHO.
ECHO now try using a SETLOCAL ENABLEDELAYEDEXPANSION command first:
ECHO.
SETLOCAL ENABLEDELAYEDEXPANSION
SET var=Original value
ECHO Before the block, %%var%%=%var% and ^^!var^^!=!var!
FOR %%i IN (1 2 3) DO (
SET var=New value %%i
ECHO loop %%i : %%var%%=%var% BUT ^^!var^^!=!var!
)
ECHO After the block, %%var%%=%var% and ^^!var^^!=!var!
ECHO.
编
addendum
呵呵,这么多的插入记号!大字不识一个兔子的天堂。
Oh, so many carets! An illiterate rabbit's paradise.
脱字符( ^
)越狱字的特殊含义,如下 - 除了%
这是由另一逃脱%
所以 - 在该行
The caret character (^
) "escapes" the special meaning of the character which follows - except for %
which is escaped by another %
So - in the line
ECHO Before the block, %%var%%=%var%
什么是呼应的是块之前,接单%
,文字 VAR
,另一个单%
, =
和 var值
What is echoed is "Before the block, " then a single %
, the text var
, another single %
, =
and the value of var
在 SETLOCAL ENABLEDELAYEDEXPANSION
字符!
成为一个特殊字符。所以
After SETLOCAL ENABLEDELAYEDEXPANSION
the character !
becomes a special character. so
ECHO Before the block, %%var%%=%var% and ^^!var^^!=!var!
或
ECHO loop %%i : %%var%%=%var% BUT ^^!var^^!=!var!
追加一个!
,字符串 VAR
,另一个单!
和 =
和 VAR的运行时间值
,因为在分析时,在 ^^
是 ^
将所得的 ^!
然后$间更换p $在执行时PTED为文字!
。在!无功!
仍然在分析时完好无损,但由在执行时 VAR
的值替换。
appends a single !
, the string var
, another single !
and =
and the run-time value of var
because at PARSE time, the ^^
is replaced by ^
and the resultant ^!
is then interpreted at EXECUTION time as a literal !
. The !var!
remains intact at PARSE time, but is replaced by the value of var
at execution time.
这篇关于停批文件只处理最后一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!