Santosh Galagali
Santosh Galagali

Reputation: 1

Renaming files with specific folder name in a file path with batch programming

I have a folder path:

C:\form\Regression\Measurments\scene1\a\file.txt
C:\form\Regression\Measurments\scene2\a\file.txt

I want the output to be:

C:\form\Regression\Measurments\scene1\a\scene1.txt
C:\form\Regression\Measurments\scene2\a\scene2.txt

I tried with below code, wasn't able to complete it:

@echo OFF

SET Dir=C:\form\Regression\Measurments

for /D /r %Dir% %%a in (*) do (
    ECHO Processing folder: %%a
    for %%b in (%%a\*.txt) do (
        setlocal EnableDelayedExpansion
        rem create here your new name of file
        set FileName=%%~nxb 
        echo File: %%b - !FileName!
        ren %%b !FileName!
    )
)

PAUSE

Upvotes: 0

Views: 70

Answers (2)

aschipfl
aschipfl

Reputation: 34909

You have got your sub-directories and files in a specific hierarchy depth, so I recomment not to use for /R: Instead use for /Dto first get the sub-directoriesscene*, then build the complete path to the filefile.txt` and rename it, given that it exists.

Here is an example of what I mean:

@echo off
rem // Enumerate the desired directory hierarchy depth:
for /D %%I in ("C:\Form\Regression\Measurements\scene*") do (
    rem // Built the full path to the file and rename when found:
    if exist "%%~I\a\file.txt" ren "%%~I\a\file.txt" "%%~nI.*"
)

Upvotes: 0

Compo
Compo

Reputation: 38613

Base solely upon the information you have provided, the following example should do as you require.

Please ensure that you modify the base directory on line 2 as necessary, (paying special attention to your spelling, as the correct spelling is 'Measurements')

@Echo Off
Set "baseDir=C:\form\Regression\Measurments"
For /D %%G In ("%baseDir%\*") Do For /D %%H In ("%%G\*"
) Do For /F "Skip=6 Tokens=3" %%I In (
    '%__AppDir__%robocopy.exe /L /NFL /NDL /NJH "%%H" Null *.txt 2^> NUL'
) Do If "%%I"=="1" (Echo Processing %%H & Ren "%%H\*.txt" "%%~nxG.txt")
Pause

To find out how it works, please read the usage information for each of the commands used.

Upvotes: 1

Related Questions