Placing words inside existing brackets or end of filename

124 Views Asked by At

I have this script that takes in a directory tree and renames files to include the words from every parent directory not yet existing in the filename.

It places the words at the end of the filename, inside brackets [], for example, the file R:\Done\Filed\The Title (2000) Creator [Rapid, Critical] xvp.dat would be renamed to The Title (2000) Creator [Rapid, Critical] xvp [Done, Filed].dat

My script:

@echo off
setlocal enabledelayedexpansion

rem set input directory
set "inputDir=%1"
set "confirmation=false"

:process
for /r "%inputDir%" %%F in (*.*) do (
    rem use path as keywords
    set "words=%%~pF"
    rem replace \ with space
    set "words=!words:\=, !"
    rem remove non-keywords
    set "words=!words: The = !"
    set "words=!words: A = !"
    set "words=!words: An = !"
    
    rem remove word if exists in filename
    for %%W in (!words!) do echo %%~nF | find /i "%%W" >nul && set "words=!words: %%W = !"
    set "newName=%%~nxF"
    rem if all words already included do not rename
    if "!words:~1,-1!"=="" set "newName=%%~nF"
    rem if exist ] in filename, replace it with the words]
    echo !newName! | find "]" && set "newName=%newName:]=!words!]%"

    rem build the name
    echo !newName! | find "]" || set "newName=%%~nF [!words:~1,-1!]%%~xF"
    rem fix "] [" caused by multiple renamings, also causes fusion with non related bracketed datasets, which is fine
    set "newName=!newName:] [= !"
    rem fix trailing ", ]"
    set "newName=!newName:, ]=]"

    rem if name has changed either echo or rename when confirmed
    if not "%%~nF"=="newName" if /i not "%confirmation%"=="yes" echo old "%%F" & echo new "!newName!"
    if not "%%~nF"=="newName" if /i "%confirmation%"=="yes" rename "%%F" "!newName!"
)

rem if coming from second (confirmed) run then exit
if /i "%confirmation%"=="yes" exit /b
rem ask for confirmation to run again for real
set /p confirmation="confirm you want to perform all these rename tasks (yes/no)?: "
if /i "%confirmation%"=="yes" goto :process

endlocal

The new version should take, for example R:\Done\Filed\The Title (2000) Creator [Rapid, Critical] xvp.dat, or R:\Done\The Title 2 (2002) Creator (Short, Critical) xvp.dat, and rename them to The Title (2000) Creator [Rapid, Critical, Done, Filed] xvp.dat, and The Title 2 (2002) Creator (short, critical) xvp [Done].dat

with the replace ] with !words!] command the newName for every file is newName:m ]=] so I wonder how to replace correctly here

0

There are 0 best solutions below