Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file - Dir's result separated

I ran into a problem while trying to finish up my own file explorer. This is the files in my working directory. I would like it to return:

FolderFoo     FileFoo
FolderBar     FileBar

However my script returns:

FolderFoo FolderBar FileFoo FileBar

Does anybody have some idea? Here's my script:

echo.|set /p some=>"%~Dp0foo\bar\FileExprTemp.tmp"

for /F "tokens=*" %%a in ('dir /B') do (
    echo.|set /p some="%%a ">>%~Dp0foo\bar\FileExprTemp.tmp
)

type %~dp0foo\bar\FileExprTemp.tmp

1 Answers

Not even a refined process, but this shows how to handle the read of the two lists in parallel while provinding a "formated" output.

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Get root folder from command line - Default to current directory
    for %%a in ("%~f1.") do set "root=%%~fa"

    rem Prepare padding for directories column
    set "folderWidth=30"
    setlocal enabledelayedexpansion
    set "padding= "
    for /l %%a in (1 1 %folderWidth%) do set "padding=!padding! "
    endlocal & set "padding=%padding%"

    rem Prepate two files to store files and directories lists
    for %%d in ("%temp%\directories.%random%%random%%random%.tmp") do (
    for %%f in ("%temp%\files.%random%%random%%random%.tmp") do (

        rem Retrieve the list of directories and files into the temp files
        dir "%root%" /b /on /ad  > "%%~fd" 2>nul 
        dir "%root%" /b /on /a-d > "%%~ff" 2>nul 

        rem Assign each temporary file to a separate stream 
        rem and call the code to process them 
        9<"%%~fd" 8<"%%~ff" call :dumpPairs

        rem Clean up temporary files
    ) & del /q "%%~ff"
    ) & del /q "%%~fd"

    rem All done, leave
    goto :eof


    rem Read stream 9 to retrieve folder name - Clean var on failure
    rem Read stream 8 to retrieve file name - Clean var on failure
    rem If both variables are uninitialized, there is nothing more to do
    rem Concatenate folder name and padding 
    rem Echo the padded folder name and file name
    rem Repeat the process

:dumpPairs
    <&9 set /p "directory=" || set "directory="
    <&8 set /p "file="      || set "file="
    if not defined directory if not defined file goto :eof

    set "line=%directory%%padding%"
    setlocal enabledelayedexpansion
    echo(!line:~0,%folderWidth%! !file!
    endlocal

    goto :dumpPairs
like image 52
MC ND Avatar answered Aug 12 '26 07:08

MC ND



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!