Parse Modified Date & Time
I have a batch script use to display a list of files's modified date & time.
This is the script's code :
for %%v in (*.html) do (
echo %%~tv
)
Que开发者_Go百科stion is, how do I parse the result into two variables. Each for date and time consecutively.
Please advice.
Regards,
Dino
If I were to solve such a problem for myself, I would do the following:
I would run that script of yours to see what output it produces. To be honest, I have run that script, and here's what I've got:
12/15/2009 08:54 AM 12/15/2009 09:30 AM 05/31/2011 07:35 PM 12/02/2009 05:53 PM 12/19/2009 09:33 PM 04/10/2010 02:07 PM 11/23/2010 03:21 PM 01/06/2010 12:03 PM
My next step then would be to determine (visually) what part of every string is the date and what part is the time, I mean, what position the substrings start at and what their lengths are.
In my case it appears to be... (where's my ruler?)
1 1 0 5 0 5 |||||||||||||||||||| 04/10/2010 02:07 PM
Ah yes, position 0, length 10 for the date and position 11, length 8 for the time. (As you can see, for strings in batch scripts I have a special ruler that starts from 0.)
Now that I know where to locate the date and the time in the output, I can extract them accordingly. But first I'd need a variable for the whole string, because extracting is applied to environment variables, not loop variables. Here:
SETLOCAL EnableDelayedExpansion FOR %%v IN (*.html) DO ( SET datetime=%%~tv ECHO !datetime:~0,10! ECHO !datetime:~11,8! ) ENDLOCAL
You might have noticed that apart from introducing a variable I also added enabling delayed expansion (of variables). This is necessary, because with the immediate expansion, i.e. like this:
FOR %%v IN (*.html) DO ( SET datetime=%%~tv ECHO %datetime:~0,10% ECHO %datetime:~11,8% )
it wouldn't work. The thing is, the
%datetime:…%
expressions would be evaluated before the loop was invoked, and thus would produce empty strings. (This peculiarity of behaviour applies to all cases where you have a bunch of commands in parentheses, whether it is aFOR
loop, anIF
orIF..ELSE
command, or even simply a redirection applied to a set of commands, like>file (commands)
.)Instead of just outputting the values you could store them in other variables to process later in the loop body:
SETLOCAL EnableDelayedExpansion FOR %%v IN (*.html) DO ( SET datetime=%%~tv SET fdate=!datetime:~0,10! SET ftime=!datetime:~11,8! :: now do whatever you like with !fdate! and !ftime! … ) ENDLOCAL
精彩评论