0

I'm using window OS, and I downloaded video as series lesson. I would like order those videos by date and adding prefix number for first video as 1 than 2, 3..... I found answer at here How to rename and add incrementing number suffix on multiple files in Batch Script? it can add number to filename, but can only order by name not date. Thank and sorry for my English.

1
  • 1
    With dir /O you can list files sorted by date (see dir /? for options); you could parse its output by a for /F loop, install a counter variable and prepend it to the file names by ren... Commented May 13, 2016 at 15:17

1 Answer 1

0

Here is a simple implementation of what aschipfl suggested in his comment:

@echo off
setlocal enableDelayedExpansion
set /a n=0
for /f "delims=" %%F in ('dir /b /od') do (
  set /a n+=1
  ren "%%F" "!n!_%%F"
)

But there are two potential problems:

1) The FOR /F command has a default EOL character of ; - if a file name were to start with ;, then it would be skipped. The simple solution is to set EOL to a character that cannot appear in a file name - : is a good choice.

2) The rename will fail if a filename contains a ! character because delayed expansion is enabled, and %%F is expanded before delayed expansion. The solution is to save the file name to a variable, and then toggle delayed expansion ON and OFF within the loop

@echo off
setlocal disableDelayedExpansion
set /a n=0
for /f "eol=: delims=" %%F in ('dir /b /od') do (
  set "file=%%F"
  set /a n+=1
  setlocal enableDelayedExpansion
  ren "!file!" "!n!_!file!"
  endlocal
)

There is a simpler option - use FINDSTR /N to prefix the DIR /B /OD output with the line number, and then use FOR /F to parse out the number and the file name. Now there is no need for a counter variable or delayed expansion.

@echo off
for /f "delims=: tokens=1*" %%A in ('dir /b /od ^| findstr /n "^"') do ren "%%B" "%%A_%%B"

You don't even need a batch file. You could use the following directly from the command line:

for /f "delims=: tokens=1*" %A in ('dir /b /od ^| findstr /n "^"') do ren "%B" "%A_%B"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.