Windows batch file:Variables in loop

2019-09-18 15:55发布

问题:

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!

回答1:

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