Search code examples
filebatch-filedirectoryparent

Batch file to list files and folders with parent directories


I have seen scripts from different people who have suggested the code denoted down below:

    @echo off
    setlocal disableDelayedExpansion
    pushd %1
    set "tab=   "
    set "indent="
    call :listFolder >report.txt
    exit /b

    :listFolder
    setlocal
    set "indent=%indent%%tab%"

    for /d %%F in (*) do (
      echo %indent%%%F
      pushd "%%F"
      call :listFolder
      popd
    )
    for %%F in (*) do echo %indent%%%F

exit /b

which outputs:

Folder 1
   Subfolder 1
      Filename 1
   Subfolder 2
      Filename 1
Folder 2
   Subfolder 1
      Filename 2
      Filename 2

This worked great for a while but I was wondering is there way to do the same idea but have the parent folder separated by a tab.

Folder 1
Folder 1    Subfolder 1
Folder 1    Subfolder 1     Filename 1
Folder 1    Subfolder 2
Folder 1    Subfolder 2     Filename 1
Folder 2
Folder 2    Subfolder 1
Folder 2    Subfolder 1     Filename 2
Folder 2    Subfolder 1     Filename 2

Solution

  • @echo OFF
    SETLOCAL
    pushd %1
    set "tab=/"
    SET "currdir=%cd%"
    call :listFolder >report.txt
    popd
    GOTO :eof
    
    :listFolder
    setlocal
    for /d %%a in (*) do (
     SET "name=%%~fa"
     SETLOCAL ENABLEDELAYEDEXPANSION
     SET name=!name:%currdir%=!
     SET name=!name:\=%tab%!
     ECHO !name!
     ENDLOCAL
     pushd "%%a"
     call :listFolder
     popd
    )
    for %%a in (*) do (
     SET "name=%%~fa"
     SETLOCAL ENABLEDELAYEDEXPANSION
     SET name=!name:%currdir%=!
     SET name=!name:\=%tab%!
     ECHO !name!
     ENDLOCAL
    )
    
    GOTO :eof
    

    Interesting exercise.

    Essentially, the report then becomes "do a dir/s/b list, but replace the \ with Tab and omit the current directory" - but that simple scheme doesn't produce the same sequence...

    ( I also replaced tab with / to make it easier to see, tabs not being particularly obvious and all ) - just a matter of choosing a character that suits...