S
S
Stanislav Valsinats2020-03-27 07:35:49
cmd/bat
Stanislav Valsinats, 2020-03-27 07:35:49

How to add parent directory name to filename?

Good afternoon, tell me:
There is a folder structure: 2016-bla1, bla2, bla3 - AAA, BBB
In each of the directories there are files like:
B010101 interesting.doc
B010201 very interesting.doc
B010302 not very interesting.doc

I need to create in the parent directories bla1 , blah 2, blah3 FOLDERS with file names. And put these folders there.

What I found, wrote, googled:

@echo off
echo "Переименовали файлы:" > C:\log.log

FOR /R "C:\БУА" %%G in (.) DO (
  Pushd %%G


  for %%A IN (*.doc) DO 	(
    for /f "tokens=1* delims= " %%B IN ("%%~nA") DO (
      echo Было:"%%~A" Стало:"%%~B" Путь "%%G"
      set z=%%G
      set str2=%z:~-4%
      echo %DATE%-%TIME% Было: "%%~A" Стало: "%%~B" Путь: "%%G" Часть пути: %z% >> C:\log.log
      If Not Exist "..\%%~B" Md "..\%%~B" >nul 2>&1
      IF Not Exist "..\%%~B\%%A" ( xcopy /y "%%A" "..\%%~B\" ) ELSE (
        

                                @rem for %%i in ( "%%G" ) do ( set name="%%~nxi" )
        @rem echo ПОЧЕМУ %name%
        @rem ren "..\%%~B\%%A" "..\%%~B\%%A%name%"
        @rem xcopy /y "%%A" "..\%%~B\"


      )
 
      )
    )
  Popd
)
pause


In the code section where it says OTHERWISE, I see that the files sometimes coincide completely in names from blah1 and blah2, I need to add the name of the parent directory to the file name so that it becomes B010101 interesting_BLA1.doc and B010101 interesting_BLA2.doc

Then the conditional operator will not be needed.

Tell me - how can I do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Valsinats, 2020-04-10
@jesterOK

I am posting the solution. Thanks to the comrade above for the variables %% and !! and the rest.

@echo off
rem - ПУТЬ МЕНЯЕМ В 3 МЕСТАХ!!!
set RoadWay=C:\test
echo "Пошла ЖАРА:" > %RoadWay%\log.log
SetLocal EnableExtensions EnableDelayedExpansion

FOR /R "%RoadWay%\" %%G in (.) DO (
  Pushd %%G

@rem Надо doc потому что учитывается doc и docx - по шаблону

  for %%A IN (*.doc) DO 	(
    set FullPath=%%~dpA
    set cut=!FullPath:~0,-1!
    for %%j in (!cut!) do set ParentDir=%%~nxj
    echo !ParentDir!
    
    for /f "tokens=1* delims= " %%B IN ("%%~nA") DO (
      
      If Not Exist "..\%%~B" Md "..\%%~B" >nul 2>&1
      IF Not Exist "..\%%~B\%%A" ( xcopy /K /y "%%A" "..\%%~B\" 
      echo %DATE%-%TIME% Скопировали "%%~A" в "..\%%~B\%%~A" >> %RoadWay%\log.log
      
      ) ELSE (

          @echo Одинаковый файл - %%A
          @echo Переименовали - %%~nA_!ParentDir!%%~xA

          ren "%%A" "%%~nA_!ParentDir!%%~xA"
          xcopy /K /y "%%~nA_!ParentDir!%%~xA" "..\%%~B\"
          echo %DATE%-%TIME% Скопировали "%%~nA_!ParentDir!%%~xA" в "..\%%~B\%%~nA_!ParentDir!%%~xA" >> %RoadWay%\log.log

      )
 
      )
    )
  Popd
)
pause

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question