Windows – How to set to a variable, the result of a expression

batch filecommand linewindows

I need to extract the date of a file, then use this string as part of the name of a new file. I tried to solve this using the next commands:

First I get the details of the file and redirect the output to a temporary file.

DIR c:/myfolder/thefile.txt >> tmp.txt

Then I use FINDSTR to get the line that contains the date, if exist a way to get only the date I didn't found it:

FINDSTR [0-9]*\/[0-9]*\/[0-9] tmp.txt

The output is:

10/04/2012 07:55 66,029 thefile.txt

Now I want to set this result to a variable:

SET vartmp=FINDSTR [0-9]*\/[0-9]*\/[0-9] tmp.txt

It seems that it worked, because when i put %vartmp% returns the result:

10/04/2012 07:55 66,029 thefile.txt

But when I try to extract a part of vartmp, begin the problems:

ECHO %vartmp:~0,2%

It's returning me the string "FI" when I expected "10", seems that vartmp is saving the expression and not the result of the expression, I'm trying assign the result of the expression to an another tempvar, then extract a substring of tempvar but nothing has changed.

Best Answer

The FOR command can be used to chop up a line into tokens so you can grab just the part you want. With /f you can run it on the output of other commands, in this case the output of DIR filtered with FIND.

for /f "tokens=1" %%a in ('dir thefile.txt ^| Find "thefile.txt"') do (
set vartmp=%%a
)
Related Question