johny
johny

Reputation: 61

Renaming files by removing the string from a specified character

I have many files in a directory each having a file name containing a - character:

M12212324-20170129ases.pdf
KlADSDFSS-sdfds20170129ases.pdf
MNSNDSNSS-20170129asdfd.pdf

Using a batch script only, I need to rename the files accordingly.

M12212324.pdf
KlADSDFSS.pdf
MNSNDSNSS.pdf

Please help me.

Upvotes: 0

Views: 488

Answers (2)

Hackoo
Hackoo

Reputation: 18827

Just copy and paste this code with your notepad or notepad++ and save it as Rename_PDF_Files.bat and drag and drop your master folder over it

@echo off
Title Rename All PDF files in folder and its subfolders with drag and drop
Mode con cols=75 lines=3 & color 0E
set "Drag_Dir=%~1"
set "Ext=pdf"
IF ["%Drag_Dir%"] EQU [""] Goto:Error
2>nul cd "%Drag_Dir%" && Call :RenamePDFfiles || Goto:Error
Explorer "%Drag_Dir%"
Exit
::********************************************
:RenamePDFfiles
echo(
echo        Please wait a while ... Renaming PDF files is in progress ...
@for /f "delims=" %%A in ('Dir /a-d /b /s "%Drag_Dir%\*-*.%Ext%"') do (
    @for /f "tokens=1 delims=-" %%B in ("%%~A") do (
        Ren "%%A" "%%~nxB.pdf"
    ) 
)
Exit /b
::********************************************
:Error
Mode con cols=75 lines=5 & Color 0C
echo(
ECHO           You must drag and drop a folder on this batch program
ECHO                      to rename all the PDF files
Timeout /T 10 /NoBreak >nul
Exit /b
::*****************************************

Upvotes: 0

Dávid Molnár
Dávid Molnár

Reputation: 11533

You can do something like this. Save this as a *.cmd script. It does rename *.PDF files in the current directory:

@echo off
setlocal

for /f "delims=" %%i in ('dir /b /a-d *.PDF') do for /f "tokens=1 delims=-" %%a in ("%%~i") do ren "%%~i" "%%a%%~xi"

... or just run this from command line:

for /f "delims=" %i in ('dir /b /a-d *.PDF') do for /f "tokens=1 delims=-" %a in ("%~i") do ren "%~i" "%a%~xi"

Upvotes: 2

Related Questions