Alex Rivera | Logout

Windows Batch help in setting a variable from command output

Asked 2009-11-17T03:54:05.050
22

I need to run a simple find command and redirect the output to a variable in a Windows Batch File.

I have tried this:

set file=ls|find ".txt"
echo %file%

But it does not work.

If I run this command it works without problems:

set file=test.txt
echo %file%  

So obviously my command output is not being set to my variable. Can anyone help? Thanks

Edit
Report

1 Answer

6

First of all, what you seem to expect from your question isn't even possible in UNIX shells. How should the shell know that ls|find foo is a command and test.txt is not? What to execute here? That's why UNIX shells have the backtick for such things. Anyway, I digress.

You can't set environment variables to multi-line strings from the shell. So we now have a problem because the output of ls wouldn't quite fit.

What you really want here, though, is a list of all text files, right? Depending on what you need it's very easy to do. The main part in all of these examples is the for loop, iterating over a set of files.

If you just need to do an action for every text file:

for %%i in (*.txt) do echo Doing something with "%%i"

This even works for file names with spaces and it won't erroneously catch files that just have a .txt in the middle of their name, such as foo.txt.bar. Just to point out that your approach isn't as pretty as you'd like it to be.

Anyway, if you want a list of files you can use a little trick to create arrays, or something like that:

setlocal enabledelayedexpansion
set N=0
for %%i in (*.txt) do (
    set Files[!N!]=%%i
    set /a N+=1
)

After this you will have a number of environment variables, named Files[0], Files[1], etc. each one containing a single file name. You can loop over that with

for /l %%x in (1,1,%N%) do echo.!Files[%%x]!

(Note that we output a superfluous new line here, we could remove that but takes one more line of code :-))

Then you can build a really long line of file names, if you wish. You might recognize the pattern:

setlocal enabledelayedexpansion
set Files=
for %%i in (*.txt) do set Files=!Files! "%%i"

Now we have a really long line with file names. Us

answered 2009-11-17T07:17:59.530

Your Answer