How to make a batch file rename a file to the date or time
There are a few different methods of how this can be done. Below is an example of how you could use the date command within the for command to extract the current date and use that data to rename the file. Each of the for commands listed in this document would be placed into a batch file.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "hope.txt" %%e-%%f-%%g.txt
Below is a breakdown of the above command and what it all means.
- for /f - The for command and the /f switch.
- "tokens=1-5 delims=/ " - How many tokens the incoming data (in this case the date) will be broken into; 1-5 is five different tokens. Finally, delims is short for delimiters and is what is used to break up the date, in this example the / (forward slash) and a space (space before the quote).
- %%d - The beginning character used for the token. Since there are 5 tokens in this example it would be d,e,f,g, and h.
- in ("%date%") - The data being used, in this case the %date% is the current date of the computer.
- do - What the for command does. The rename command can be substituted for anything else.
- rename "hope.txt" %%e-%%f-%%g.txt - Rename the file "hope.txt" to the tokens e,f, and g with a .txt file extension. This example also has a - (hyphen) in-between each token to separate the month, day, and year in the file name.
When %date% is used in a batch file it displays the date in the following format: Sun 09/02/2007 this command breaks this date into the tokens: "Sun" (%%d), "09" (%%e), "02" (%%f), and "2007" (%%g).
In this example, using the above date mentioned hope.txt would be renamed to 09-02-2007.txt.
for /f "tokens=1-5 delims=:" %%d in ("%time%") do rename "hope.txt" %%d-%%e.txt
This command is very similar to the above example. However, instead of using the forward slash and space to break up the data we're using a : (colon) because the time is split up with this character. Finally, because we're renaming the file to only the hour and minute this example is only using the d and e token. Additional information about what everything in this line means is found in the above date example.
When %time% is used in a batch file it displays the time in the following format: 19:34:52.25, this command breaks this time into the tokens: "19" (%%d), "34" (%%e), and "52.25" (%%f).
In this example, using the above time mentioned hope.txt would be renamed to 19-34.txt.