Lastwish
Lastwish

Reputation: 327

Batch Script - Obtain all files with multiple extensions

List all files with multiple extensions into a text file.

Below code works fine :

 dir /s/b *.jpg /s *.png > temp.txt

But, if pwd is desktop and i need to find all files from a particular user directory and its sub directories (Ex : C:\Users\user_name) and the text file should be created in my pwd i.e Desktop in this case. I tried the below code, but it contains all files existing without considering the extension.

dir C:\Users\<user_name>\ /s/b *.jpg /s *.png > temp.txt

Upvotes: 1

Views: 3896

Answers (2)

cbuchart
cbuchart

Reputation: 11575

Though some years late, I'd like to share the script I usually use for this same task. It will receive the directory and a list of extensions (expressed as wildcards: *.jpg).

In your case, an example of use would be this_script.bat . *.jpg *.png > files.txt

@echo off

setlocal

rem %1 Directory to list
rem %2 - %9 extensions

if "%2"=="" (
    echo Usage %0 ^<directory^> ^<extensions separated by space^>
    echo Example: %0 . *.jpg *.jpeg *.png *.bmp *.gif
    exit /b 1
)

set EXTENSIONS=%2 %3 %4 %5 %6 %7 %8 %9

pushd %1

rem List files in base directory
call :list_dir %cd%

rem List subdirectories
for /F "delims=" %%D in ('dir /ad /on /b /s') do (
    call :list_dir %%D
)

popd

exit /b 0

rem Lists all files in a directory that match the extensions
:list_dir
pushd %1
set DIR=%1

for %%S in (%EXTENSIONS%) do (
    echo %DIR%\%%S
)

popd
exit /b 0

If you require a list in a variable just change the echo in :list_dir by the expression you need.

Upvotes: 0

Stephan
Stephan

Reputation: 56228

switches for dir are "global", so adding a switch several times doesn't change anything.

dir /s /b C:\Users\<user_name>\*.jpg C:\Users\<user_name>\*.png >temp.txt

or

pushd C:\Users\<user_name>\
dir /s /b *.jpg *.png>%userprofile%\desktop\temp.txt
popd

or more elegant:

( pushd C:\Users\<user_name>\
dir /s /b *.jpg *.png
popd ) >temp.txt

if you really want /b/s for *.jpg and only /s for *.png, you will have to work with two dircommands.

EDIT for getting the extensions from a simple textfile:

pushd C:\Users\<user_name>\
(for /f %%e in (extensions.txt) do (
  dir /s /b *%%e
)) >temp.txt
popd

extensions.txt should look like this:

.jpg
.png
.gif

If the textfile looks different, this code has to be adapted accordingly.

Upvotes: 1

Related Questions