user1131435
user1131435

Reputation:

Change latter part of file name, but not extension, in batch

I'm trying to rename the latter part of a file, before the extension, in a batch script.
For instance:

block1.txt --> block1-%mydate%-%mytime%.txt

block2.zip --> block2-%mydate%-%mytime%.txt

The file name is passed to the program as %1. Only one file name will be changed per run. The program is intended to append a time-stamp to the end of a file, in the form of MMDDYYYY-HHMM.

The first part of the program produces the expression %mydate%-%mytime%.

I can't for the life of me figure out how to do it in a generic and consistently functional way.

Any help?

Upvotes: 0

Views: 484

Answers (2)

James K
James K

Reputation: 4055

Did you mean: FileName-MMDDYYYY-HHSS.*

for /f "tokens=2-7 delims=/:. " %%a in ("%date% %time: =0%") do set newFileName=%~n1-%%a%%b%%c-%%d%%f%~x1
ren "%~1" "%newFileName%"

Or did you mean: FileName-MMDDYYYY-HHMM.*

for /f "tokens=2-6 delims=/:. " %%a in ("%date% %time: =0%") do set newFileName=%~n1-%%a%%b%%c-%%d%%e%~x1
ren "%~1" "%newFileName%"

Upvotes: 1

Desislav Kamenov
Desislav Kamenov

Reputation: 1203

For Windows here is what @hobodave answered to a similar question:

For command-line

for /F %i in ("c:\foo\bar.txt") do @echo %~ni

output: bar

For .bat Files

set FILE=bar
for /F %%i in ("%FILE%") do @echo %%~ni

output: bar

Further Reading:

http://www.computerhope.com/forhlp.htm

For Unix

You can use the basename command. It will clear path and extension from a given path.

basename /foo/bar/arch.zip .zip

Will output

arch

Basename manual: http://unixhelp.ed.ac.uk/CGI/man-cgi?basename

Upvotes: 1

Related Questions