[英]Windows batch file:Variables in loop
I am trying to copy files recursively and then rename them according their containg folder name. 我试图递归地复制文件,然后根据其containg文件夹名称重命名它们。
I am trying to extract folder name from path. 我正在尝试从路径提取文件夹名称。 So far I got this but id does not work: 到目前为止,我得到了这个,但是id不起作用:
SET "MyPath=C:\MyFolder\"
SETLOCAL EnableDelayedExpansion
FOR /R "%MyPath%" %%F DO (
ECHO "%%~pF" :: ~pF expands F to a path only
:: this is in my case a variable (length of a file that comes froma function call)
SET /a intFileLength=5
SET strPathOnly=%%~pF
SET folderName=!strPathOnly:~-intFileLength!
ECHO "Extracted folder name: " !folderName!
)
endlocal
This is my echo 这是我的回声
Extracted folder name: " strPathOnly:~-intFileLength 提取的文件夹名称:“ strPathOnly:〜-intFileLength
SET /a intFileLength = 5
:: The following works
SET folderName=!strPathOnly:~-5!
:: This one does not work
SET folderName=!strPathOnly:~-intFileLength!
Your FOR loop is a mess - a FOR loop cannot work without an IN() clause. 您的FOR循环是一团糟-如果没有IN()子句,FOR循环就无法工作。 I can only guess what your intent is. 我只能猜测你的意图是什么。
Regardless, you cannot do substring operations on FOR variables - you must store the value in an environment variable before you manipulate it. 无论如何,您不能对FOR变量执行子字符串操作-必须先将值存储在环境变量中,然后才能对其进行操作。 Also, you must transfer the count to a FOR variable so that you can use it as a substring argument within delayed expansion. 另外,必须将计数传输到FOR变量,以便可以将其用作延迟扩展内的子字符串参数。
@echo off
SETLOCAL EnableDelayedExpansion
SET "MyPath=C:\MyFolder\"
FOR /R "%MyPath%" %%F in (*) DO (
set "str=%%~pF"
SET /a suffixToExtractLength=5
for %%N in (!suffixToExtractLength!) do SET "result=!str:~-%%N!"
ECHO Extracted characters: !result!
)
endlocal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.