问题
I'm looking for way to rename multiple files with a batch job. Yes, I know there are many Applications around which can achieve this. But I need an automated way, something like a Batch File which I can call from a Scheduler (SOS Job Scheduler). We need to rename hundreds of files daily!
The Goal is to set the 17-25 charcaters at the beginning of the file.
- 00010028229720270014468393_TB-E.pdf -> 00144683930001002822972027_TB-E.pdf
- 000100282297202700144683931ESR-AF.pdf -> 001446839300010028229720271ESR-AF.pdf
- 00010031141040250016353371ESR-AF.pdf -> 00163533700010031141040251ESR-AF.pdf
- 0001003167580004001667217KTO.pdf -> 0016672170001003167580004KTO.pdf
Here an example which is more clearer:
0001 002822972 027 001446839 _TB-E .pdf -> 001446839 0001 002822972 027 _TB-E .pdf
回答1:
@ECHO OFF
SETLOCAL
SET "sourcedir=c:\sourcedir"
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*" '
) DO (
SET "name=%%a"
CALL :transform
)
GOTO :EOF
:transform
ECHO REN "%sourcedir%\%name%" "%name:~16,9%%name:~0,16%%name:~25%"
GOTO :eof
The required REN commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO REN
to REN
to actually rename the files.
Note that the very first example you've presented has ...393_TB-E... in the transformed version, that 3
is missing.
回答2:
This can be accomplished very simply with the help of REPL.BAT - a hybrid JScript/batch utility that performs a regex search and replace on each line from stdin and writes the result to stdout. The utility uses only native scripting capabilities that are available to any modern Windows machine from XP onward; no 3rd party executable required. Complete documentation is embedded within the script.
Assuming REPL.BAT is somewhere within your PATH:
@echo off
pushd "c:\sourcePath"
for /f "delims=" %%A in (
'dir /b /a-d *.pdf ^| repl "(.{16})(.{9}).*" "ren \q$&\q \q$2$1*\q" x'
) do %%A
popd
Using only native batch commands, without any CALL:
@echo off
setlocal disableDelayedExpansion
pushd "c:\sourcePath"
for /f "delims=" %%F in ('dir /b /a-d *.pdf') do (
set "file=%%F"
setlocal enableDelayedExpansion
ren "!file!" "!file:~16,9!!file:~0,17!*"
endlocal
)
popd
If you know that none of your file names contain the !
character, then you can simply enable delayed expansion at the top, and remove both SETLOCAL and ENDLOCAL from within the loop.
Both solutions above rely on the fact that *
at the end of the target name will preserve the remainder of the original file name. See How does the Windows RENAME command interpret wildcards? for more info.
回答3:
(\d{16})(\d+)(.*?\.pdf) -> \2\1\3
{16} means you take 16 repetitions (of a digit)
来源:https://stackoverflow.com/questions/21162119/regular-expression-in-a-windows-batch-file