This is probably a super-simple already solved task, but:
I have a series of folders containing eBooks in various formats. They have the folder name format:
\Lastname, Firstname (n books)\
I want to rename each of the folders to be simply
\Firstname Lastname\
which I'm guessing can be done with a batch file fairly easily, but it's been a very long time since I had to do string parsing so I have no recollection of how.
Help? I'm using Windows 7.
Answer
Assuming spaces are consistent with your example (i.e. Firstname and Lastname don't have spaces), this should work.
@echo off
setlocal EnableDelayedExpansion
for /f "tokens=1,2,*" %%a in ('dir /a:d /b') do (
set lastname=%%a
set lastname=!lastname:~0,-1!
ren "%%a %%b %%c" "%%b !lastname!"
)
endlocal
It just splits by spaces, and trims the comma off the Lastname, of all directories in the same directory as the batch file.
If the names can have spaces, some delimiter manipulation is necessary. I'll go fiddle with that.
Edit:
Here we go. Fiddling with delimiters means Firstname was surrounded by a space before and after it, which had to be trimmed out. So essentially, it expects a Lastname
followed by a ,
followed by a
Firstname
followed by a
(whatever
. The spaces around Firstname are important (and are there in your example). Spaces within the names work fine.
@echo off
setlocal EnableDelayedExpansion
for /f "tokens=1,2,* delims=,(" %%a in ('dir /a:d /b') do (
set firstname=%%b
set firstname=!firstname:~1,-1!
ren "%%a,%%b(%%c" "!firstname! %%a"
)
endlocal
You may wish to have a test run, by putting an echo
before the ren
, to make sure it works as expected.
No comments:
Post a Comment