2016-10-31 4 views
3

Я пытаюсь:Генерация файлов папка файла list.txt в поддиректории директории/и переименовать list.txt в папку/имени подпапки с помощью реж & REN команды в пакетном файле

  1. список содержимое каждого папку в подпапке в текстовом файле,
  2. поместите текстовый файл в родительскую папку, а также в подпапку,
  3. переименуйте выходной текстовый файл как имя родительской папки/подпапки.

Для достижения этой цели я попытался следующий пакетный скрипт

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 

Теперь

  1. Я могу список файлов каждой папки,
  2. __List.txt создается,
  3. __List.txt переименовывается в подпапку.

Проблема:

  1. Пустые папки не является печать.
  2. Если какой-либо каталог уже есть «каталог/подкаталог name.txt», получаю эту ошибку

    Имя дубликатов файлов существует или файл не найден

  3. Ошибка время отображения в окне консоли. (Предпочтительным методом может быть создание журнала ошибок и размещение его в родительской папке.) Однако это необязательно.

могут быть следующие ссылки в то время как ответ, так как часть запроса размещены индивидуально в них:

  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

Пример структуры папок:

  • Родительская папка
    • Sub Папка-01
      • __filelist.txt
        Созданный со списком содержимого с помощью командырежи преобразуется вSub Folder-01.txt.
      • некоторые-данные-файлы 1.xyz
      • некоторые-файлы данных 2.
      • XYZ
      • некоторые-Data-файлы 3.xyz
    • Sub Папка-02-Empty
      • Sub-Sub Папка-01
        • __filelist.txt
          Возможная причина для «Файл уже существует» ошибка.
        • some-Data-files_A.xyz
        • some-Data-files_B.xyz
        • some-Data-files_C.xyz
      • __filelist.txt
        Не генерируется из-за пустой папки. Возможная причина позади 'файл не найден' ошибка.
    • batch_file.bat
    • __filelist.txt
    • some-file.xyz

может потребоваться два раза раствором

  1. Команда dir команда должна генерировать filelist.txt, даже если папка пуста, она разрешит ошибку «файл не найден».

  2. Команда жэнью должна перезаписать существующие filelist.txt или переименовать существующий filelist.txt в filelist1-100.txt в дополнительном порядке. Он может разрешить ошибку «файл уже существует».

+0

@Mofi, Что я могу сказать ... Ваш ответ бриллиантовой превосходна-фантастическим. Именно то, чего я пытался достичь. Вы хорошо объяснили, что позволило мне легко настроить и изменить. Большое спасибо. (Глупый Q) Кстати, где зеленая кнопка галочки, чтобы принять этот ответ? – manaswin

+0

@mofi просто сталкивается с проблемой со сценарием в папке, где присутствует lacs файлов, показывающих «Система не может найти указанный путь». Он хорошо работает в папках, где присутствует небольшое количество файлов. – manaswin

+0

Что вы подразумеваете под 'where lacs of files present?? Я не понимаю эту фразу. Примечание. Максимальная длина для пути к папке ограничена в процессе команды Windows до MAX_PATH (260). Подробнее см. В разделе [Почему в Windows существует ограничение длины пути 260 символов?] (Http://stackoverflow.com/questions/1880321/) Запущено это ограничение из-за слишком большого количества или слишком длинных имен папок в дереве папок ? – Mofi

ответ

0

Попробуйте комментировал пакетный файл:

@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. 

Пакетный файл записывает в каждый файл списка папок только имена подпапок и файлов в этой папке.

Например Sub Folder-02-Empty.txt содержит только

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

И Sub-Sub Folder-01.txt содержит для данного примера:

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

Читать комментарии для того, что делать исключения файла списка, если имя файла списка должен не включаться в файл списка.

Чтобы понять используемые команды и как они работают, откройте окно командной строки, выполните там следующие команды и тщательно прочитайте все страницы справки, отображаемые для каждой команды.

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