Windows批处理文件:变量在循环 [英] Windows batch file:Variables in loop

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

问题描述

我想递归地复制文件
然后他们根据自己的containg文件夹名称重命名。


我想从路径中提取文件夹名称。
到目前为止,我得到这个,但id不工作:

 
SETmypath中= C:\\ MyFolder文件\\SETLOCAL EnableDelayedExpansionFOR / R%mypath中%%% f执行(    ECHO%%〜PF::〜pF的扩展F到一个路径    ::这是我的情况下,一个变量(一个文件的长度自带弗罗马函数调用)
    SET / A intFileLength = 5
    SET strPathOnly = %%〜pF的    SET FOLDERNAME = strPathOnly:〜!-intFileLength!
    ECHO提取的文件夹名称:文件夹名!
)ENDLOCAL




这是我的回声

解压的文件夹名称:strPathOnly:〜-intFileLength

 
    SET / A intFileLength = 5    ::下面的作品
    SET FOLDERNAME = strPathOnly:-5〜!    ::这一次不起作用
    SET FOLDERNAME = strPathOnly:〜!-intFileLength!


解决方案

您FOR循环是一个烂摊子 - FOR循环离不开一个IN()子句工作。我只能猜测你的意图是什么。

无论如何,你不能做对的子串变量的操作 - 你操纵它之前,你必须存储在一个环境变量的值。此外,还必须伯爵转移到FOR变量,以便用户可以使用它作为延迟扩展中的一个子的说法。

 关闭@echo
SETLOCAL EnableDelayedExpansion
SETmypath中= C:\\ MyFolder文件\\FOR / R%mypath中%%% f由于(*)DO(
  设置海峡= %%〜PF
  SET / A suffixToExtractLength = 5
  (!suffixToExtractLength)对%% N的做SET结果= STR:!〜 - %% N
  ECHO提取字符:!结果!

ENDLOCAL

I am trying to copy files recursively and then rename them according their containg folder name.
I am trying to extract folder name from path. So far I got this but id does not work:


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


    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. 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. Also, you must transfer the count to a FOR variable so that you can use it as a substring argument within delayed expansion.

@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

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

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