Batch renaming files before certain character

521 views Asked by At

I have a bunch of Pdf files with names like so:

Malcolm Gaskill - History.pdf 
Manfred B. Steger - Globalization; A Very Short Introduction.pdf  

I want to rename them to get rid of everything before the first hyphen so they end up like:

History.pdf 
Globalization; A Very Short Introduction.pdf

How do I go about doing this? Thanks

1

There are 1 answers

1
Magoo On
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%sourcedir%\*-*.pdf" '
 ) DO (
 FOR /f "tokens=1*delims=-" %%b IN ("%%a") DO (
  FOR /f "tokens=*" %%d IN ("%%c") DO (
   ECHO(REN "%sourcedir%\%%~a" "%%~d"
  )
 )
)
GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

Not particularly easy for a beginner, since the filenames may contain ; which is a separator like Space

First, perform a dir /b to get all of the required filenames which are applied to %%a using for /f with no delimiters.

Next, tokenise using - into %%b and %%c, then remove leading separators from %%c using tokens=* applying required filename to %%d.

Then mix-and-match to build the required rename command.