批处理-在for循环中设置变量 [英] Batch - Set variables in for loop

查看:1025
本文介绍了批处理-在for循环中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试进行一些批合并和重命名,并且遇到了以下问题(这不是实际的代码,而是展示问题的MWE):

I'm currently trying to do some batch merging and renaming and am facing the following problem (this is not the actual code, but rather a MWE demonstrating the problem):

@echo off
set /p "arg=Input the path to target directory (defaults to current directory if left empty): "

for %%f in ("%arg%\*.mkv") do (
  echo %%~nf
  set "out=%%~nf"
  echo %out%
)

pause

我的问题是,这两个回声不能打印相同的值.第一个打印正确的内容(文件名),第二个打印随机的内容,例如Echo为OFF或目录的最后一个文件名.

My problem is that these two echoes do not print the same values. The first one prints the correct thing (file name), the second one prints something random like Echo is OFF or the last file name of the directory.

经过一番搜索,我发现提到了使用延迟扩展变量(setlocal EnableDelayedExpansion),但是这引起了一个问题,因为用户输入的目录路径可能包含感叹号,如果这样做,它们会被删除.因此for循环根本不会执行.

After a bit of searching I found a mention of using delayed expansion of variables (setlocal EnableDelayedExpansion), but that causes a problem, because the directory path the user inputs may contain exclamation marks, which get removed if I do that (and so the for loop is not executed at all).

如何正确地在for循环中设置变量?

How do I properly go about setting variables in a for loop?

借助Dennis的解决方案和一些其他的反复试验,我终于能够修复原始代码,并且现在可以使用了.对于任何有兴趣的人,这就是我正在尝试做的事情:

With the help of Dennis's solution and some additional trial and error, I was finally able to fix the original code and it now works. For anyone interested, this is what I was attempting to do:

for %%f in ("%arg%\*.mkv") do (
  set "n=%%~nf"

  setlocal EnableDelayedExpansion
  mkvmerge -o "!n:~15,10! !n:~25!" "!n!_Track00.h264" ...
  endlocal
)

实际上,实际命令要长得多,因此我没有完整地粘贴它,只是粘贴了足够的内容以演示它作为参数所需要的内容.我使用变量n是因为%%〜nf在延迟扩展环境中无法正常运行(即!s被删除),而且我不知道如何在延迟扩展中取消引用双精度变量(参数?).

The actual command is in fact much longer so I'm not pasting it in its entirety, just pasting enough to demonstrate what is required in it as arguments. I used the variable n because %%~nf does not function well inside the delayed expansion environment (i.e. the !s get removed), and I don't know how to dereference double-percented variables (parameters?) with delayed expansion.

另外,尝试

set "out=%n:~15,10% %n:~25%"

在设置延迟扩展后再运行

before setting delayed expansion and then running

mkvmerge -o "!out!" ...

没有适当地延迟扩展,所以上面的代码就是我最终得到的.

did not delay expansion properly so the above code was what I ended up with.

推荐答案

您应该尝试以下操作:

@echo off
set "arg=."
set /p "arg=Input the path to target directory (defaults to current directory if left empty): "
for %%f in ("%arg%\*.mkv") do (
  echo %%~nf
  set "out=%%~nf"
  setlocal EnableDelayedExpansion
  echo !out!
  endlocal
)
pause

这篇关于批处理-在for循环中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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