Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
    
What OS are you using? –  Paul Apr 12 '12 at 5:12
    
@Paul: Right, that would have been helpful info, wouldn't it? ;) Windows 7. –  Margaret Apr 12 '12 at 5:13

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.