Tuesday, June 16, 2009

Datestamps in batch files. (Unix and Dos)

In Linux, naming a file after todays date is pretty easy.

# Note: These are backticks, not quotes.
# They are on the same key as your tilde ~.
ls > `date %Y-%m-%d.`txt

To get the possible formatting options, run the man date command.

In Dos it is pretty easy too, once you know the trick.

dir > %date:~-4,4%-%date:~-7,2%-%date:~-10,2%.txt


An Explanation:
The %date% environment variable contains the current date. Go ahead, test it. Pop open a command prompt and run echo %date%. The ":~-4,4" part does the cool thing. ":~" says "we want a substring". The "-" says "work from the end of the string backwards. The "4," says start at the fourth character, and the final "4" says give me four characters.

Cheat sheet!





Date PartCode
Day of week (3 letter abbr.)%date:~0,3%
Day%date:~-10,2%
Month%date:~-7,2%
Year (2 digits)%date:~-2,2%
Year (4 digits)%date:~-4,4%


HTH,
-Ellie

No comments: