3

I need a script that will allow me to strip filenames to files that are placed within folders, and apply the folder names to the files, and add an incremental number to the end of each filename.

So the filenames would look something like this in their original state:

gdgeregdja34gtj.jpg

And then look like this after the script is executed:

foldername>foldername001.jpg
foldername>foldername002.jpg

I have this script, which allows the folder name to prefix any filename of files within folders. But it doesn't strip the filenames.

@echo off
 pushd "Folder"
  for /d %%D in (*) do (
    for %%F in ("%%~D\*") do (
     for %%P in ("%%F\..") do (
    ren "%%F" "%%~nxP_%%~nxF"
  )
 )
)
popd
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
  • Is this to work in a single folder or over an entire tree? Will the number continue over a whole tree or start from 001 in each folder? – foxidrive Sep 10 '13 at 23:43
  • I want the script to work on multiple folders. What I want to do is execute the script from within a folder that has many folders. Upon executing the script the files within the folders will be stripped of their names (but the extensions retained) and replaced with the names of their respective folders. And each file will have an increment of 1 (0001, 0002, 0003, etc). "Will the number continue over a whole tree or start from 001 in each folder?" The number will start from "0001" in each folder. – Bill Stimpson Sep 11 '13 at 15:20
  • If the answer works for you then make sure you accept (click on the tick) so that others in the future, with a similar issue, know that it's worth a try. – foxidrive Sep 16 '13 at 05:08

1 Answers1

0

This will echo the rename commands to the screen, so if it does what you want then remove the echo to make it work.

Filenames with ! characters will not be renamed.

@echo off
 setlocal enabledelayedexpansion
  for /d /r %%a in (*) do (
    set n=0
    pushd "%%a"
      for /f "delims=" %%b in (' dir /b /a-d 2^>nul ') do (
        set /a n=n+1
           set num=0000!n!
           echo ren "%%b" "%%~nxa!num:~-4!%%~xb"
    )
   popd
  )
pause
foxidrive
  • 40,353
  • 10
  • 53
  • 68
  • Thank you foxidrive! When I run the batch script it works, even though the terminal reads, "The system cannot find the path specified." But it works, so it's no big deal. Could you tell me how I can modify the script to put a spaced hyphen before the incremental numbers? So the filename would look like this: "crimson - 0001.jpg" – Bill Stimpson Sep 15 '13 at 19:31
  • Alter this `"%%~nxa!num:~-4!%%~xb"` to this `"%%~nxa - !num:~-4!%%~xb"` and the error message is because you didn't change `pushd "c:\folder"` to the location you need to use. I removed them above as you appear to be using the current folder. – foxidrive Sep 16 '13 at 01:20