manaswin
manaswin

Reputation: 41

Generate file-folder list.txt file in a directory/subdirectory & rename list.txt to folder/subfolder name using dir & ren command in a batch file

I am trying to :

  1. list contents of each folder in a subfolder in a text file,
  2. place the text file in parent folder as well as subfolder,
  3. rename the output text file as name of parent folder/subfolder.

To achieve that I have tried following batch script

del /s __List.txt
for /F "delims=" %%G IN ('dir /b /s') DO @echo "%%G">>"%%~__List.txt"
for /r %%a in (__List.txt) do for %%b in ("%%~dpa\.") do ren "%%~a" "%%~nxb%%~xa"
pause

Now

  1. I am able to list files of each folder,
  2. __List.txt is being created,
  3. __List.txt is being renamed as subfolder.

Problem is:

  1. Empty folders not being printing.
  2. If any directory already have "directory/Subdirectory Name.txt", getting this error

    A duplicate file name exists or the file cannot found

  3. Error being displaying in console window. (Preferred method may be create a error log and place the same in parent folder.) It's optional however.

Following can be referenced while answer since part of query posted individually in them:

  1. .bat rename files in folders/sub-folders to specific name
  2. Batch Files: List all files in a directory, print as .txt and place output file in all sub directories
  3. Batch File - Rename files based on parent name and (sub)folder(s) name

Example of folder structure:

Two fold solution may required

  1. Command dir command should generate filelist.txt even if folder is empty, it will resolve 'file not found' error.

  2. Command ren should overwrite existing filelist.txt or rename existing filelist.txt to filelist1-100.txt in incremental order. It may resolve 'file already exists' error.

Upvotes: 4

Views: 1276

Answers (1)

Mofi
Mofi

Reputation: 49096

Try this commented batch file:

@echo off
setlocal
if "%~1" == "" goto UseCD

rem The start folder is either the current folder on running the batch file
rem or the folder specified as first argument on starting the batch file.
rem All / (Unix/Mac) in specified folder path are replaced by \ (Windows).
rem The folder path must not end with a backslash for this task.

set "StartFolder=%~1"
set "StartFolder=%StartFolder:/=\%"
if "%StartFolder:~-1%" == "\" set "StartFolder=%StartFolder:~0,-1%"
if exist "%StartFolder%\" goto CreateLists

rem The environment variable CD (Current Directory) holds the entire path
rem to the current folder ending not with a backslash, except the current
rem folder is the root folder of a drive.

:UseCD
if not "%CD:~-1%" == "\" (
    set "StartFolder=%CD%"
) else (
    set "StartFolder=%CD:~0,-1%"
)

rem The error log file in start folder existing perhaps from a previous
rem run is deleted first before the list file is created recursively in
rem each folder of the start folder.

:CreateLists
set "ErrorLogFile=%StartFolder%\Error.log"
%SystemRoot%\System32\attrib.exe -h -r -s "%ErrorLogFile%" >nul
del "%ErrorLogFile%" 2>nul

call :RecursiveList "%StartFolder%"

endlocal

rem Avoid an unwanted fall through to the subroutine.
goto :EOF


rem RecursiveList is a subroutine called for each folder found
rem in the start folder and its subfolders.

rem For the root folder of a drive like C: the list file name is "DriveC.txt".
rem For all other folders the list file name is "Folder Name.txt".

rem The command DEL does not delete a file which has hidden, read-only or
rem system attribute set. For that reason ATTRIB is called first to remove
rem those attributes from a perhaps already existing list file in current
rem folder. ATTRIB outputs an error message because of not existing file
rem to handle STDOUT which is the reason for >nul which redirects this
rem not important error message to device NUL.

rem Next the list file is deleted with suppressing the error message output
rem by command DIR to handle STDERR with 2>nul if the file does not exist
rem at all. But in case of the file really exists and could not be deleted
rem (NTFS permissions, file access denied because file is opened in another
rem application), an error message is logged into error log file in start
rem folder which is hopefully not write-protected, too.

rem Creating a list file in a folder is skipped if there is already
rem a list file and it could not be deleted by command DEL.

rem Otherwise the command DIR is used to write first the names of the
rem subfolders in alphabetical order according to name (not alphanumeric)
rem into the list file of current folder and next append the names of all
rem files in current folder also ordered by name. The name of the list file
rem is included in list file. Comment the two lines with command DIR and
rem uncomment the 3 lines below to avoid this by first writing the folder
rem and files names into a list file in temporary files folder and then
rem move this list file with correct list file name to the current folder.

rem Last for each subfolder in current folder the subroutine RecursiveList
rem calls itself until all subfolders in current folder have been processed.

:RecursiveList
set "FolderPath=%~1"
if "%FolderPath:~2%" == "" (
    set "ListFileName=Drive%FolderPath:~0,1%.txt"
) else (
    set "ListFileName=%~nx1.txt"
)

%SystemRoot%\System32\attrib.exe -h -r -s "%FolderPath%\%ListFileName%" >nul
del "%FolderPath%\%ListFileName%" >nul 2>&1
if exist "%FolderPath%\%ListFileName%" (
    echo Failed to update: "%FolderPath%\%ListFileName%">>"%ErrorLogFile%"
    goto ProcessSubFolders
)

dir /AD /B /ON "%FolderPath%">"%FolderPath%\%ListFileName%" 2>nul
dir /A-D /B /ON "%FolderPath%">>"%FolderPath%\%ListFileName%" 2>nul

rem dir /AD /B /ON "%FolderPath%">"%TEMP%\%~n0.tmp" 2>nul
rem dir /A-D /B /ON "%FolderPath%">>"%TEMP%\%~n0.tmp" 2>nul
rem move "%TEMP%\%~n0.tmp" "%FolderPath%\%ListFileName%"

:ProcessSubFolders
for /D %%I in ("%FolderPath%\*") do call :RecursiveList "%%~I"
goto :EOF

rem The command above exits the subroutine RecursiveList. The batch
rem file processing is continued in previous routine which is again
rem the subroutine RecursiveList or finally the main batch code above.

The batch file writes into each folder list file just the names of the subfolders and the files in this folder.

For example Sub Folder-02-Empty.txt contains just

Sub-Sub Folder-01
Sub Folder-02-Empty.txt

And Sub-Sub Folder-01.txt contains for the given example:

__filelist.txt
some-Data-files_A.xyz
some-Data-files_B.xyz
some-Data-files_C.xyz
Sub-Sub Folder-01.txt

Read the comments for what to do to exclude the list file if the file name of the list file should not be included in the list file.

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

  • attrib /?
  • call /?
  • del /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?

Upvotes: 1

Related Questions