USMC-3537
USMC-3537

Reputation: 13

Change File Name to Folder Name

I've been working on a batch script (.bat) to change file name to the same folder name 3 levels up but no luck. I can only get it to rename 1 level up. There are multiple files in multiple folders.

Any help would be greatly appreciated.

Upvotes: 1

Views: 254

Answers (2)

dbenham
dbenham

Reputation: 130839

I don't completely understand the intent of your current code. But the following will rename a given file based on the folder 3 levels up. Note that you can only rename one file with a given extension per folder using this strategy.

@echo off
setlocal
set "file=H:\Techs\Exported Videos\Scenario\1-CAS IED\Media player format\A8 West\abc.avi"
for %%A in ("%file%") do for %%B in ("%%~A\..\..\..") do ren "%%~A" "%%~nxB%%~xA"

Note that I include the extension of the folder name because folder names can include dots.

EDIT

Based on OP's comments, I believe the following will properly rename all relevant .avi files. The code has been tested, and works in my hands. Simply set the root and files values as appropriate.

@echo off
setlocal
set "root=H:\Techs\Exported Videos\Scenario"
set "files=*.avi"

for %%A in ("%root%\.") do set "root=%%~fA"
for /f "delims=" %%A in ('dir /b /s /a-d "%root%\%files%"') do (
  for %%B in ("%%~A\..\..\..") do (
    if /i "%%~dpB" equ "%root%\" ren "%%~A" "%%~nxB%%~xA"
  )
)

Upvotes: 1

Endoro
Endoro

Reputation: 37569

you might try this:

@echo off &setlocal
set /a PathLevel=3
for %%a in (
    "H:\Techs\Exported Videos\Scenario\1-CAS IED\Media player format\A8 West\1-CAS IED.avi"
    "H:\Techs\Exported Videos\Scenario\2-SAF\Media player format\A8 PTZ\2-SAF.avi"
    ) do (
    call:doit "%%~a"
)
goto:eof

:doit
set "fname=%~1"
set /a cnt=0
for %%a in ("%fname:\=","%") do set /a cnt+=1
set /a cnt-=PathLevel
for %%a in ("%fname:\=","%") do (
    set /a cnt-=1
    setlocal enabledelayedexpansion
    if !cnt! equ 0 (
        endlocal
        set "nname=%%~a"
    ) else endlocal
)
echo ren "%fname%" "%nname%%~x1"
goto:eof

output is:

ren "H:\Techs\Exported Videos\Scenario\1-CAS IED\Media player format\A8 West\1-CAS IED.avi" "1-CAS IED.avi"
ren "H:\Techs\Exported Videos\Scenario\2-SAF\Media player format\A8 PTZ\2-SAF.avi" "2-SAF.avi"

Upvotes: 1

Related Questions