Renaming part of filename

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
airkemp
Posts: 5
Joined: 03 Oct 2011 09:29

Renaming part of filename

#1 Post by airkemp » 10 Oct 2011 06:30

Hi,

I have a load of files THAT ALL START WITH "Test"

Test3526.bmp
Test5486.bmp
Test9073.bmp
Test6759.bmp
Test1674.bmp
etc

I want to rename only the "Test" part to something else e.g;

Something3526.bmp
etc

Any Ideas

Cheers

Alex

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Renaming part of filename

#2 Post by dbenham » 10 Oct 2011 11:44

You just need a FOR loop combined with variable substrings. Use HELP FOR, and HELP SET from the command line to get help on these topics.

From the command line:

Code: Select all

for %F in (*.bmp) do set "name=%~nF"&call ren "%F" "Something%name:~4%.bmp"


From within a batch file

Code: Select all

@echo off
for %%F in (*.bmp) do (
  set "name=%%~nF"
  call ren "%%F" "Something%%name%%:~4%.bmp"
)

Both of the above will work as long as file names do not contain %

This will work if name contains %, but will not work if it contains !:

Code: Select all

@echo off
setlocal enableDelayedExpansion
for %%F in (*.bmp) do (
  set "name=%%~nF"
  ren "%%F" "Something!name%%:~4!.bmp"
)


The principles behind this answer will also work for your previous post Removing numbers from file names

Dave Benham

Post Reply