问题
I want to rename files and transfer them into a library using a batch file in the following way:
c:\jg_Folder_xy>
blabla01_000.bla --> blabla01_001.bla
blabla02_000.bla --> blabla02_001.bla
blabla03_000.bla --> blabla03_001.bla
c:\sj_Folder_mx>
blabla01_000.bla --> blabla01_002.bla
blabla02_000.bla --> blabla02_002.bla
blabla03_000.bla --> blabla03_002.bla
c:\an_Folder_kj>
blabla01_000.bla --> blabla01_003.bla
blabla02_000.bla --> blabla02_003.bla
blabla03_000.bla --> blabla03_003.bla
and than transfer all into a new folder
c:\New_Folder>
blabla01_001.bla
blabla01_002.bla
blabla01_003.bla
blabla02_001.bla
blabla02_002.bla
blabla02_003.bla
blabla03_001.bla
blabla03_002.bla
blabla03_003.bla
anyone knows what is the most efficient way?
NOTE: folders name have only one sub string in common
回答1:
How to do it
Here's a simple solution in batch:
@echo off
setlocal enabledelayedexpansion
set "SRC_PATH=c:\jg_Folder_xy"
set "DEST_PATH=c:\New_Folder"
for %%f in ("%SRC_PATH%"\*.bla) do (
set fname=%%~nf
set fbase=!fname:~0,-4!
set findex=!fbase:~-2!
move %%f "%DEST_PATH%"\!fbase!_0!findex!%%~xf
)
Note: this script has to be run on each source folder separately (changing SRC_PATH
each time). Alternatively, you can modify the for
loop to a double loop, like so:
for /d %%d in (*_Folder_*) do for %%f in ("%%d"\*.bla) do (
so that it'll iterate automatically over all files in all desired folders (the SRC_PATH
line won't be needed).
How it works
The for
loop iterates over the files in the source folder, and assigns the filename (with the full path) to %%f
in each iteration.
set fname=%%~nf
extracts the filename and drops the extension.
set fbase=!fname:~0,-4!
obtains all but the last 4 characters (i.e. drops the "_000").
This essentially extracts the base filename, which is "blabla01", "blabla02"... in your example.
set findex=!fbase:~-2!
extracts the last 2 characters from the fbase
, i.e. the running index.
It is assumed that the running index is exactly two characters.
The move
command renames the files and moves them into the destination folder.
Hope this helps.
来源:https://stackoverflow.com/questions/12047690/rename-and-move-files-in-batch-dos