Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to extract the date of a file, for then use this string as part of the name of a new file. I trying 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 wanna 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.

share|improve this question
Give us the complete script. I can figure out how you set vartmp. – JasonXA Apr 18 '15 at 11:14

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
share|improve this answer

It's not ideal, but could change SET vartmp=FINDSTR [0-9]*\/[0-9]*\/[0-9] tmp.txt to

FINDSTR [0-9]*\/[0-9]*\/[0-9] tmp.txt > tmp2.txt
SET /p vartmp =< tmp2.txt
DEL tmp2.txt
share|improve this answer

When following your examples I found same result however if I replaced the line:

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


for /f %i in ('FINDSTR [0-9]*\/[0-9]*\/[0-9] tmp.txt') do set vartmp=%i

then vartmp holds what you seek. Note that you need single quotes there, double quotes won't work. Also if using in a batch file you need %%i in place of %i

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .