Add folder name to beginning of filename

Posted by shekhar on Super User See other posts from Super User or by shekhar
Published on 2012-12-07T06:19:21Z Indexed on 2012/12/10 11:11 UTC
Read the original article Hit count: 295

I have a directory structure as below:

Folder
  > SubFolder1
    > FileName1.abc
    > Filename2.abc
    > .............

  > SubFolder2
    > 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 the folder name at the beginning of the file name with the delimiter "_". The directory structure should remain unchanged. Note: Beginning of file name is same. e.g. in above case File*.

I made below Script


for /r "PATH" %%G in (.) do (

pushd %%G

for %%* in (.) do set MyDir=%%~n*

FOR %%v IN (File*.*) DO REN %%v "%MyDir%_%%v" popd )


Problem with the above script is that it is taking only one Subfolder name and placing it to the beginning of file name irrespective of the folder.

© Super User or respective owner

Related posts about Windows

Related posts about command-line