2

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.

1
  • 1
    Give us the complete script. I can figure out how you set vartmp.
    – JasonXA
    Apr 18, 2015 at 11:14

3 Answers 3

1

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
)
0

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
3
  • Its just sad that it has to be done this way on windows..... Feb 10, 2021 at 7:22
  • @Antoniossss you can make really simple microservices in .NET Core now. So basically just use C# instead May 1, 2021 at 2:27
  • @Antoniossss Did you check it out dude? It's FOSS and will run on anysystem. Jul 7, 2021 at 1:26
0

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

with

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.