Current Articles
  Archived Articles
  TECHS Articles
  Current Projects
  About Us
You are not logged in.

Please either Login or create a New Account.
Custom RSS

Note: this links is the RSS feed for the current filters shown at the top of the page. For an RSS feed for all articles in this community, click here
Tag
DOS (1)
What makes many windows system admins cringe?  BATCH FILES  Well, truth is they are not for the faint of heart.  But batch files are just way too handy. 
I just was presented by a colleague a problem of renaming a file to incorporate the date in the filename.  Kindof a handy thing to do in coordination with other batch type tasks.  Well, I wish I'd figured this one out, but thanks to the internet I have a cute little command that can be added to batch files or run from the command prompt to incorporate the date into a filename. 

Here are the pieces. 

1.  GET THE DATE - If you type "echo %date%" into a command prompt you will get a lovely presentation of the date.  This is an environment variable.  All environment variables are precedded and followed by a %. Today looks like "Thu 04/02/2009"

2.  FORMAT THE DATE - This is what got me... the date has slashes in it.  Pretty much a no no for a filename, so we need to strip out the important info from the %date%.  Well, there is a convention for extracting bits of a blob of text.  In the date environemet variable we can follow the word date with a colon (:) a tilde (~) and two numbers separated by a comma to indicate the start position and number characters to extract from the larger bit of text.  For example: if we want just the month from the day ("Thu 04/02/2009") we type the following. 
%date:~4,2 

the result is...
04

This is the result of skipping 4 characters and capturing the next 2. 
Yipee! we have the month... following the same idea we can get the day, and year also.
 (come on you know you want to open up a command line and give it a try...)
Lots more information on this page...http://www.dostips.com/DtTipsStringManipulation.php

3.  RENAME THINGS - The rename command is much simpler to deal with than the date formatting.  All you need to do is type RENAME or REN followed by two parameters.  First is the filename as it is currently, and then the filename you want it to be.  Like this...

REN nate.txt sexy.txt

Ya, all of you reading this are having error messges flash in your brain.  Remember to place each parameter in double quotes if there happen to be spaces in the file name or path to the file.

4.  PUT IT ALL TOGHETHER - Ok well put all those pieces together and we now have the tools to rename a file called happy.txt to 2009-04-02happy.txt by using the folloing command...

REN happy.txt %date:~10%-%date:~4,2%-%date:~7,2%happy.txt

This works by concatenating the year, month, day, and other text in the target filename.
Year = %date:~10%
Month = %date:~4,2%
Day = %date:~7,2%

Give it a go!
Tags: DOSexamples



  1