Home > Software engineering >  How to rename a file to the parent's parent folder name in batch
How to rename a file to the parent's parent folder name in batch

Time:01-12

so I have a bunch of folders with similar directories to the below:

.\page\1\randomStringofCharacters\randomStringofCharactersAgain.png
.\page\2\randomStringofCharacters\randomStringofCharactersAgain.png
.\page\3\randomStringofCharacters\randomStringofCharactersAgain.png

I want to rename all the .png files the number just before the first randomStringofCharacters. So basically

.\page\1\randomStringofCharacters\randomStringofCharactersAgain.png -> 1.png
.\page\2\randomStringofCharacters\randomStringofCharactersAgain.png -> 2.png
.\page\3\randomStringofCharacters\randomStringofCharactersAgain.png -> 3.png

Is there any batch script that can do this? I have tried:

@Echo OFF

FOR /D /R %%# in (*) DO (
    PUSHD "%%#"
    FOR %%@ in ("*.png") DO (
        Echo Ren: ".\%%~n#\%%@" "%%~n#%%~x@"
        Ren "%%@" "%%~n#%%~x@"
    )
    POPD
)

Pause&Exit

Yet this only renames the file with the parent directory.

And if possible is there a way to move all such renamed .png files in to a newly made folder in .\page\ (the same place where the .bat is) with the folder name of page?

Thanks in advance!

CodePudding user response:

Could be something like this (you have to drag and drop the main folder to the batch):

@echo off

if exist "%~1" (IF not exist "%~1\" exit) else (exit)
if /i not exist "%~dp0Page" md "%~dp0Page"

pushd "%~1"
for /f "delims=" %%a in ('dir /s /b *.png') do Call :Rename "%%~a" "%%~dpa"
exit

:Rename
set Cpath=%~2
set Cpath=%Cpath:~0,-1%
For %%a in ("%Cpath%") do set Cpath=%%~dpa
set Cpath=%Cpath:~0,-1%
for %%a in ("%Cpath%") do set NName=%%~nxa
move "%~1" "%~dp0Page\%NName%%~x1"
goto :EOF

enter image description here

CodePudding user response:

You should not use for /R to handle items in a predefined directory hierarchy depth:

@echo off
rem // Iterate through the numeric target sub-directories (`1`, `2`, `3`, etc.):
for /D %%K in (".\page\*") do (
    rem // Iterate through sub-sub-directories `randomStringofCharacters`:
    for /D %%J in ("%%~K\*") do (
        rem // Iterate through `.png` files:
        for %%I in ("%%~J\*.png") do (
            rem // Actually rename the current file:
            ren "%%~I" "%%~nxK%%~xI"
        )
    )
)

Note, that this approach does not check whether there is only one .png file at each location.

  •  Tags:  
  • Related