I have this kind of files naming system
CR - Plan - Grundriss_RO_STA_MA_C7_TS_0001_01_F - Plan Nord.pdf
and I would like to have a .bat file that removes the parts before and after and changes the files names to
Grundriss_RO_STA_MA_C7_TS_0001_01_F.pdf
The parts before and after do not always have the same length!
I will be very thankful if you could help! Thank you very much.
This code could be used copied into a batch file saved into the directory with the files to rename.
@echo off
for /F "eol=| delims=" %%I in ('dir /A-D /B *-*-* 2^>nul') do (
for /F "eol=| tokens=3 delims=- " %%J in ("%%~nI") do ren "%%I" "%%J%%~xI"
)
I recommend to insert command ECHO left to command REN and run the batch file from within a command prompt window with current directory being the directory with the files to rename to first verify if the files would be renamed as expected. If everything looks right, run the batch file with the code as posted.
The outer FOR loop runs DIR to get a list of only file names because of the parameters /A-D
(attribute not directory) and /B
(bare output format) of files having at least two dashes in file name. "eol=| delims="
defines a vertical bar as end of line character which no file name can contain ever to process also correct file names starting with ;
and defines an empty list of string delimiters to disable the default of splitting each output line of DIR into strings using normal space and horizontal tab character as delimiters.
The inner FOR loop processes just the name of each file without file extension referenced with %%~nI
in double quotes. Of interest for this task is just the third part of a file name after two sequences of spaces and dashes. This is the reason for "eol=| tokens=3 delims=- "
.
The command REN renames the current file as returned by DIR to just third part and original file extension referenced with %%~xI
.
Double quotes must be used wherever a file name is referenced as the file names contain spaces.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
echo /?
for /?
ren /?
2^>nul
redirects the error message output by command DIR to handle STDERR in case of no file matching the pattern *-*-*
found to the device NUL to suppress it. The redirection operator >
must be escaped here with ^
to be interpreted as redirection operator on execution of command DIR and not as misplaced redirection operator for command FOR. See also the Microsoft documentation about Using command redirection operators.