Reputation: 37
I want to automate some actions with a batch script, one thing I have to do, is to replace a date on a file, with the current date. I tried to do something, dut it's like the line of my file is empty...
SET planningFile=<My file with full path>
set mydate=%date:~6,4%%date:~3,2%%date:~0,2%
FOR /F %%i IN ('TYPE "%planningFile%"') DO (
SET str=%%i
SET str=%str:~8,%
ECHO %mydate%%srt% > "%planningFile%~"
)
DEL "%planningFile%"
RENAME "%planningFile%~" "%planningFile%"
a line of that file looks like 20140513;54;aaaa:54
(CSV file).
Anyone could help me ?
Upvotes: 0
Views: 51
Reputation: 80023
Within a block statement (a parenthesised series of statements)
, the entire block is parsed and then executed. Any %var%
within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block)
.
Hence, IF (something) else (somethingelse)
will be executed using the values of %variables%
at the time the IF
is encountered.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion
and use !var!
in place of %var%
to access the changed value of var
or 2) to call a subroutine to perform further processing using the changed values.
Hence
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F %%i IN ('TYPE "%planningFile%"') DO (
SET "str=%%i"
SET "str=!str:~8!"
ECHO %mydate%!sTR! > "%planningFile%~"
)
Note : - your line has `ECHO ...%srt% ....
The >
should be >>
if you wish to append rather than create the file anew.
See any number of SO articles on delayedexpansion
for hundreds of examples.
Upvotes: 1