Sharma
Sharma

Reputation: 21

Renaming a file based on existing text in file name using batch scripts only

How can I used batch commands to rename a file based upon existing text in name? For example, if I have a file named:

abc-pqr123Jan20151321f

I might need to rename it to

q~hello~Jan-2015~zz.

I will always need to use the month and year already present in the file name; it will always be at the same place in the source file name. Other characters in the name can be any random text. Month and year will change for all months.

I'd like to rename just one file at a time. Only batch commands are to be used.

Upvotes: 0

Views: 947

Answers (2)

Endoro
Endoro

Reputation: 37569

Try this:

@echo off &setlocal disabledelayedexpansion
set "FilePath=C:\test\abc-pqr123Jan20151321f"
for %%a in ("%FilePath%\*") do set "FileName=%%~nxa"
set "NewName=q~hello~%FileName:~10,7%~zz"
echo ren "%FilePath%\%FileName%" "%NewName%"

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

C:\Temp> set f=abc-pqr123Jan20151321f

C:\Temp> set x=q~hello~%f:~10,7%~zz

C:\Temp> echo %x%
q~hello~Jan2015~zz

C:\Temp> _

The constraint “Only batch commands are to be used” is a bit unclear and weird. What commands quality as “batch commands”? And why on Earth restrict yourself to those?

If this is homework, then please, for future such questions, state in the question that it's homework, because that affects how we best can help you.

Upvotes: 0

Related Questions