Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add date and time to filename in DOS?

Tags:

batch-file

I want to add date and time value in filename and then I want to move that file to near by folder.

Here I'm using below commands to capture date and time :

set dt=%date:~7,2%-%date:~4,2%-%date:~10,4%_%time:~,8%

echo %dt%

Then I am using copy command as below :

copy result_accnum.txt C:\ramki_windows\batch_practise\Query_stored\result_accnum_%dt%.txt

but nothing useful. I am getting error as "The filename, directory name, or volume label syntax is incorrect.".

like image 382
ramki_ramakrishnan Avatar asked Apr 22 '14 17:04

ramki_ramakrishnan


1 Answers

FOR /f "tokens=1-8 delims=:./ " %%G IN ("%date%_%time%") DO (
SET datetime=%%G%%H%%I_%%J_%%K
)

This will calculate it as date_hour_min_sec and store it in a variable called as datetime. e.g.

24042015_19_10_12

you can use this datetime variable directly appended to your filename if you know how to do it in DOS (its simple : set filename= sampletextfor_%datetime%.txt will give you sampletextfor_24042015_19_10_12.txt or whatever file).


how it works?

the for command goes through the string formed by %date%%time%. %date%%time% gives you the value of date time in cmd (system variables). the token specifies which elements do you want to pick up based on the delimiter. the delimiter specifies what to consider as a new element say for e.g. /:. are delims here. also " " (space) is a delimiter (you can see I have left one after /)


Hope it helps thanks! :)

like image 179
Sarthak Avatar answered Oct 08 '22 09:10

Sarthak