简体   繁体   English

仅一行cmd:替换文件名不起作用?

[英]BATch one line cmd: Replace filename doesnt work?

I'm trying to replace an file name but it doesnt work. 我正在尝试替换文件名,但是它不起作用。

I know that this works: (command line, no .bat file!) 我知道这可行:(命令行,没有.bat文件!)

SET G="test string"
echo %G:s=a%

But if i use a for loop it doesnt work. 但是,如果我使用for循环,它将无法正常工作。 Why? 为什么? (command line, no .bat file!) (命令行,没有.bat文件!)

for /r . %G in (*.jpg) do echo %G:s=a%

Thanks for help in Advance! 感谢您的帮助提前!

A for loop in a BAT needs to double the "%%". BAT中的for循环需要将“ %%”加倍。 Also, the for variable doesn't support substitutions, and variables get substituted before executed. 另外,for变量不支持替换,并且变量在执行前被替换。

For /r . 对于/ r。 %%G in (*.jpg) do @echo %%G (* .jpg)中的%% G执行@echo %% G

Try this: 尝试这个:

setlocal ENABLEDELAYEDEXPANSION
for %%g in (*.JPG) do @set Q=%%g && echo !Q:t=X!

You are confusing a Batch variable with a FOR command replaceable parameter . 您正在将Batch变量与FOR命令的可替换参数混淆。 In these lines: 在这些行中:

SET G="test string"
echo %G:s=a%

The G is a Batch variable, but in this one: G是一个Batch变量,但在此变量中:

for /r . %G in (*.jpg) do echo %G:s=a%

The G is a FOR replaceable parameter and the substring replacement only works on Batch variables. G是一个FOR可替换参数,子字符串替换仅适用于Batch变量。 The solution is to assign the FOR parameter into a Batch variable and then do the replacement. 解决方案是将FOR参数分配给Batch变量,然后进行替换。 However, the only way to do so is via delayed expansion , so the solution is this: 但是,唯一的方法是通过延迟扩展 ,因此解决方案是这样的:

cmd /V:ON /C for /r . %G in (*.jpg) do @set "G=%G" ^& echo !G:s=a!

For further details, search this site for "delayed expansion" or type cmd /? 有关更多详细信息,请在此站点上搜索“延迟扩展”或键入cmd /? and set /? set /? , and carefully read "delayed expansion" references. ,并仔细阅读“延迟扩展”参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM