Link to home
Start Free TrialLog in
Avatar of scrathcyboy
scrathcyboyFlag for United States of America

asked on

Batch to strip file name prefixes

I have about 1500 files that are prefixed with --  "1 - "  (that is one, space, hyphen, space) up to -- "1500 - "

I need a batch to get the file name and strip out this prefix of -- number, space, hyphen, space -- essentially to rename all the files in a single directory.  I can put the batch in the same directory to make it easier.

Second part of question -- after the number is "The" or "the"  in some cases --   748 - The ... rest of name ...
So let's also strip out  "the" or "The" if it occurs just after hyphen-space (but not elsewhere in the name).

Third,  I'd like the renamed files copied to a different directory if possible -- either rename them all in place, or copy the newly named files to a different folder -- don't want 2 copies of each file in the one folder.

MANY Thanks for your help.
Avatar of Qlemo
Qlemo
Flag of Germany image

@echo off
setlocal enabledelayedexpansion
for /F "delims=- tokens=1*" %%F in ('dir /b "* - *") do ren "%%F - %%G" "%%G"
for %%F in ("The *") do (set n=%%F& ren "%%F" "!n:~4!"

Avatar of scrathcyboy

ASKER

wow, I would have never figured that out.  Is it safe to do * - * though?  Say there was one file without the number prefix, space, hyphen, space -- would that strip the entire file name out?  Might it be best to do a number check instead of the first asterisk ?
get the error -- system cannot find the file dir /b * - *

adjust it to work on all files in the current directory only, I will put the batch in where I want to strip
It is not 100% safe. But there is no direct way to use wildcard for numbers only, so that check could by tricky. Let's do it this way:

Since digits are "Less" then letters, this will work

@echo off
setlocal enabledelayedexpansion
for /F "delims=- tokens=1*" %%F in ('dir /b "* - *") do if "%%F" LSS "A" ren "%%F - %%G" "%%G"
for %%F in ("The *") do (set n=%%F& ren "%%F" "!n:~4!"

Open in new window

Ooops, missing quote ...



@echo off
setlocal enabledelayedexpansion
for /F "delims=- tokens=1*" %%F in ('dir /b "* - *"') do if "%%F" LSS "A" ren "%%F - %%G" "%%G"
for %%F in ("The *") do (set n=%%F& ren "%%F" "!n:~4!"

Open in new window

I use dir /b to suppress unneeded dir info. But you will have to start it in correct directory, else rename will throw errors. But you can avoid this if you use move instead, so paths are not doing any harm.

I used your last one above, and get repeating message -- system cannot find the file specified.

you are getting closer though.  
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Brilliant work Olemo, you got it perfect.  Thanks !!