%% F变量始终引用FOR循环中的最后一项而不是当前项 [英] %%F variable always referencing the last item in a FOR loop instead of the current one

查看:189
本文介绍了%% F变量始终引用FOR循环中的最后一项而不是当前项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎应该是相当简单的,但是我很难在DOS中获得一个FOR循环来正确地报告它正在评估的当前项目.

This seems like is should be fairly simple, but I am having trouble getting a FOR loop in DOS to correctly report the current item it is evaluating.

我有一个简单的DOS批处理文件,该文件循环遍历目录中的所有文件并重命名它们.例如,假设我的目录包含以下文件:

I have a simple DOS batch file that loops through all files in a directory and renames them. Let's say for example my directory contains the following files:

File1.txt
File2.txt
File3.txt

我想从每个文件中删除TXT扩展名.所以我的批处理命令看起来像:

I want to remove the TXT extension from each file. So my batch command looks something like:

@回声关闭

for %%F in ("*.txt") do (
  echo %%F
  set tmpFile=%%F
  echo %tmpFile%
  set newFile=%tmpFile:~0,-4%.xml
  echo %newFile%
)

我的预期输出将是:

File1.txt
File1.txt
File1.xml
File2.txt
File2.txt
File2.xml
File3.txt
File3.txt
File3.xml

相反,输出为:

File1.txt
File3.txt
File3.xml
File2.txt
File3.txt
File3.xml
File3.txt
File3.txt
File3.xml

好像将%% F设置为变量总是使用集合中的最后一个文件.

It's as if setting %%F to a variable always uses the last file in the collection.

我做错什么了吗?请注意,我知道有更好的方法来简单地更改扩展名.我完成的批处理文件将执行更多操作,但是我似乎无法超越这个初始步骤.

Am I doing something wrong? Please note I know there are better ways to simply change an extension. My finished batch file will perform many more actions, but I can't seem to get past this initial step.

推荐答案

这是因为要在for循环中设置和访问变量.

It's because you are setting and accessing a variable within a for loop.

您需要使用延迟扩展来访问它们,而使用!而不是%.

You need to use delayed expansion to access them, using !'s instead of %'s.

setlocal enabledelayedexpansion
for %%F in ("*.txt") do (
  echo %%F
  set tmpFile=%%F
  echo !tmpFile!
  set newFile=!tmpFile:~0,-4!.xml
  echo !newFile!
)

这篇关于%% F变量始终引用FOR循环中的最后一项而不是当前项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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