0

This is bascially a continuation of answered question but with additional condition

Add folder name to beginning of filename

I have a directory structure as below:

Folder
  > SubFolder1xxxx
    > FileName1.abc
    > Filename2.abc
    > .............

  > SubFolder2xxxx
    > FileName11.abc
    > Filename12.abc
    > ..............

  > ..........

etc. I want to rename the files inside the subfolders as:

SubFolder1_Filename1.abc
SubFolder1_Filename2.abc
SubFolder2_Filename11.abc
SubFolder2_Filename12.abc

i.e. add part of the folder name at the beginning of the file name with the delimiter "_". The directory structure should remain unchanged.

I have below Script


for /d %D in (*) do (
  for %F in ("%~D\*") do (
    for %P in ("%F\..") do (
      ren "%F" "%~nxP_%~nxF"
    )
  )
)

Problem with the above script is that it is taking the whole folder name

hence I tried to extract only part of the filename using syntax substring

 %variable:~num_chars_to_skip,num_chars_to_keep%

So I modify above code with it, but it gave me error :(

for /d %D in (*) do (
      for %F in ("%~D\*") do (
        for %P in ("%F\..") do (
          ren "%F" "%~nxP:~0,10%_%~nxF"
        )
      )
    )

the error is basically the syntax subtring do not work, it just print it as a string. somthing like this

SubFolder1xxxx:~0,10%

1 Answers1

0

Example batch which gets batch file's folder name.

@echo off
set a=%~p0%
for /f "tokens=1,2,3,4,5,6,7,8,9 delims=\" %%a in ("%a%") do call :getlast %%a %%b %%c %%d %%e %%f %%g %%h %%i
goto :eof
:getlast
if "%1"=="" goto :eof
if "%2"=="" echo Current folder name is %1.
shift
goto :getlast

Current restrictions: not more than 9 subfolder levels (edit, parse slack if needed), no spaces in names (edit, add quoting if needed).

Akina
  • 3,295