Search code examples
cmdcommand-prompt

How to list only paths via CMD


I'm trying to list paths to all files with specific extension on my hard drive.

I am using dir *.txt /s /b and this is my output:

C:\Path\To\File\1.txt
C:\Path\To\File\2.txt
C:\Path\To\File\3.txt
C:\Path2\To\File\1.txt

But instead of that I need only paths to those files, without duplicates and filenames. So in that cast it would be:

C:\Path\To\File\
C:\Path2\To\File\

any help welcome


Solution

  • A batch file processed by the Windows Command Processor cmd.exe for listing all directories containing at least one file with file extension .txt on system drive is:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    set "PreviousDirectory="
    for /F "delims=" %%I in ('dir %SystemDrive%\*.txt /A-D-L /B /S 2^>nul') do (
        set "CurrentDirectory=%%~dpI"
        setlocal EnableDelayedExpansion
        if not "!PreviousDirectory!" == "!CurrentDirectory!" (
            endlocal
            echo %%~dpI
            set "PreviousDirectory=%%~dpI"
        ) else endlocal
    )
    endlocal
    

    There is started one more command process in background to run the command DIR of which output is captured by the command process which is processing the batch file. It can take for that reason several seconds or even minutes before any output is displayed at all as there is first searched the entire system drive for all files with file extension .txt not being a link before the list of file names is processed by command FOR.

    There could be used also a batch file with the following command lines:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    if exist "%SystemDrive%\*.txt" echo %SystemDrive%\
    for /D /R "%SystemDrive%\" %%I in (*) do if exist "%%I\*.txt" echo %%I\
    endlocal
    

    That outputs the directory paths while searching through the entire system drive. But it can result in false positives if a directory contains a directory or a link ending with .txt in name. This solution does also not output directories with hidden attribute set containing a file with file extension .txt. The first solution is therefore better.

    To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

    • dir /?
    • echo /?
    • endlocal /?
    • for /?
    • if /?
    • set /?
    • setlocal /?