2

Given a directory with the following files

image1.txt
image2.txt
image3.txt

I want to get the oldest file (let the files be sorted by data, oldset date first):

dir /b /od c:\test\image?.txt | findstr ^1

That works great when manually typing it into cmd.exe. Now (in a batch script) I want to put the output of this command in a variable. How can I do this? Thank you!

Update: Wondering if there is a direct way without usng a loop?

stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

4 Answers4

3
For /F %%A in ('"dir /b /od C:\test\image*.txt|findstr ^1"') do set myVar=%%A

You could do it through For loop, try that in command line, I just tested it and it works fine

Output:

set myVar=image1.txt

On executing Set on command line you can see:

myVar=image1.txt
NUMBER_OF_PROCESSORS=2
Gerold Meisinger
  • 4,500
  • 5
  • 26
  • 33
Habib
  • 219,104
  • 29
  • 407
  • 436
  • Thank you, I updated my question, I am wondering if there is a way without the loop – stefan.at.kotlin Apr 12 '12 at 20:15
  • 1
    You should avoid expressions like `set myVar=%A`, as it creates a variable with a space, so you have to use `%myVar %`/`%myVar%` to expand it – jeb Apr 12 '12 at 20:32
  • @stefan.at.wpf I don't know of any other way than using a temporary file as jeb has already mentioned in his answer – Habib Apr 13 '12 at 05:40
2

There isn't a direct way, the FOR-Loop is one way or the other way is set /p with a temporary file.

dir /b /od c:\test\image?.txt | findstr ^1 > oldest.tmp
< oldest.tmp set /p myVar=
jeb
  • 78,592
  • 17
  • 171
  • 225
0

Example:

wmic path Win32_VideoController get CurrentHorizontalResolution | FINDSTR [0-9] > X.txt 'Output in a file
wmic path Win32_VideoController get CurrentVerticalResolution | FINDSTR [0-9] > Y.txt
wmic path Win32_VideoController get CurrentRefreshRate | FINDSTR [0-9] > Hz.txt
wmic path Win32_VideoController get CurrentBitsPerPixel | FINDSTR [0-9] > Bits.txt
set /p X= < X.txt 'Input from a file
set /p Y= < Y.txt
set /p Hz= < Hz.txt
set /p Bits= < Bits.txt
set X=%X: =% 'Remove the spaces
set Y=%Y: =%
set Hz=%Hz: =%
set Bits=%Bits: =%
DEL /q X.txt 'Delete file created
DEL /q Y.txt
DEL /q Hz.txt
DEL /q Bits.txt

Four steps.

-2

set variableName = dir /b /od C;\test\image?.txt | findstr ^1

note: this is untested. Source:

Google

  • I also expected this behaviour before posting here, but it's not working that way for outputs of other commands – stefan.at.kotlin Apr 12 '12 at 20:15
  • And it doesn't work. cmd.exe will only set `variableName` to `dir /b /od C;\test\image?.txt` but will not execute it. But as there is a pipe it will execute `findstr 1` in a new cmd-context. And at the end even `variableName` will be empty. – jeb Apr 12 '12 at 20:40