I have many pdf files I need to Copy, Rename and Move.
Copy and move works – I just can’t figure out how the rename part it’s done.
The files look like this:
2021-05-05_10-10-12-609_Testperson_Nancy_2512489996_19490816_OD_20210429112706.pdf
2021-06-05_11-11-12-135_Testperson_with_many _Names_0708681234_19490817_OD_20210429112715.pdf
and I need them to be renamed to:
251248-9996_19490816_OD_20210429112706.pdf
070868-1234_19490817_OD_20210429112715.pdf
So need to substring from the fourth _
from the right (without the first _
) with a -
between [6] and [7].
This is what I got so far:
SET input=c:\temp\rename\input
SET backup=c:\temp\rename\backup
SET output=c:\temp\rename\output
if not exist "%backup%" mkdir "%backup%"
for /f "tokens=*" %%F IN ('DIR /S /B "%input%\*.pdf"') DO (
xcopy /-y "%%F" "%backup%" & move "%%F" "%output%"
)
c:\temp\rename\input
(for original files)
c:\temp\rename\backup
(backup dir for orginal files)
c:\temp\rename\output
(renamed files)
This must be run as a scheduled batch file job on Windows Server (I know how to run the job)
Give this a go. I would suggest you first make a backup of your files before running this in on your production files:
@echo off & setlocal enabledelayedexpansion
set "input=c:\temp\rename\input"
set "backup=c:\temp\rename\backup"
set "output=c:\temp\rename\output"
mkdir "%backup%">nul 2>&1
for /f "delims=" %%i in ('dir /b /s /a-d "%input%\*.pdf"') do (
set "cnt=-4"
set "_tmp=%%~i"
set "_tmp=!_tmp: =-!
set "_strip=!_tmp:_= !"
for %%c in (!_strip!) do (
set /a cnt+=1
)
if !cnt! gtr 1 if defined _tmp call :parser !cnt! "%%i"
)
goto :eof
:parser
for /f "tokens=%~1,* delims=_" %%a in ("%~2") do set "fin=%%~b"
echo xcopy /-y "%~2" "%backup%"
echo move "%~2" "%output%\%fin:~0,6%-%fin:~6%"
Some things to note. This does not yet do the actual copy
or move
, it will just echo
the results, as a safety measure. So once you see it does what it should, then you can remove echo
from the last two lines.
Lastly this is assuming the file format as you gave it, but it does cater for whitespace as well as double _
but it will go south if you have another _
separated section which does not form part of the standard format.
Demo
Given the 4 examples you gave in your question and comment (with the exception of the C:\tmp\Input
in my example as I use a different directory to test):