Reputation: 29
I would like to get the time stamp from the last two lines in a file that looks something like this using DOS:
2/3/2013 18:30:00 This is line 1 2/3/2013 19:24:05 This is line 2 2/3/2013 20:10:40 This is line 3 2/3/2013 21:06:00 This is line 4 2/3/2013 22:50:31 This is line 5
Currently, my script looks like this:
setlocal EnableDelayedExpansion
set i=0
for /f "tokens=2" %%x in (inputfile.txt) do (
set /a i=!i!+1
set time!i!=%%x
)
set /a lasttime=time!i!
set /a j=!i!-1
set /a prevtime=time!j!
echo %lasttime%
echo %prevtime%
endlocal
The output only have the hours portion, no minutes and seconds:
21
22
Please tell me how to make it work.
Upvotes: 2
Views: 624
Reputation: 77657
The issue is your using the SET /A
command for assigning lasttime
and prevtime
.
SET /A
is used for arithmetic operations, and everything you are feeding it must be converted to a number, even though you are not doing anything with the value apart from storing it to another variable. Your time!i!
reference evaluates to 22:50:31
but in the context of the SET /A
command it is immediately converted to the closest numeric value, which is 22
. Same happens with time!j!
.
To fix the issue, just use a simple SET
command and mixed expansion, like this:
...
set lasttime=!time%i%!
set /a j=!i!-1
set prevtime=!time%j%!
...
Also, if all you need is the last two lines, you could consider an alternative approach. Instead of using a separate variable for every line of the text, you could use just two: one to store the current line, the other to store the previous value of the former. Here's what I mean:
setlocal EnableDelayedExpansion
for /f "tokens=2" %%x in (inputfile.txt) do (
set prevtime=!lasttime!
set lasttime=%%x
)
echo %lasttime%
echo %prevtime%
endlocal
Upvotes: 2