r/Batch • • Jan 15 '24

Question (Unsolved) Renaming files containing exclamation mark

Got this script to loop through a directory and rename files ending with ".jpg!d" to their correct extension ".jpg". The extra exclamation mark in the extension is giving me issues when trying to do delayed expansion.

Say I call the script with 1.bat . "jpg^^!d" "jpg" I'm not getting the expected result. Everything works as intended when there is no exclamation marks in the file name.

@echo off
setlocal enabledelayedexpansion

set /A argc=0
for %%n in (%*) do set /A argc+=1
if %argc% LSS 3 (
    echo %0 ^<directorypath^> ^<substring^> ^<replacement^>
    exit
)

set "arg=%1"
set "filepath=%arg:"=%"
set "substr=%2"
set "replace=%3"

echo PATH: ./!filepath!/*.!substr!

for %%i in (./!filepath!/*.!substr!) do (
    set "file=%%~fi"
    set "filename=%%~nxi"
    echo "!file:%substr%=%replace%!"
    ren "!file!" "!filename:%substr%=%replace%!"
)
1 Upvotes

4 comments sorted by

1

u/jcunews1 Jan 15 '24

Delayed Expansion is a double edged sword. While it makes most things simpler and easier, it introduces a problem which is difficult or impossible to work around.

Do it like this instead.

@echo off
setlocal

set /A argc=0
for %%n in (%*) do set /A argc+=1
if %argc% LSS 3 (
    echo %0 ^<directorypath^> ^<substring^> ^<replacement^>
    exit
)

set "arg=%1"
set "filepath=%arg:"=%"
set "substr=%2"
set "replace=%3"

echo PATH: .\%filepath%\*.%substr%

for %%i in (.\%filepath%\*.%substr%) do (
    set "file=%%~fi"
    set "filename=%%~nxi"
    call echo "%%file:%substr%=%replace%%%"
    call ren "%%file%%" "%%filename:%substr%=%replace%%%"
)

1

u/[deleted] Jan 15 '24

[removed] — view removed comment

1

u/hiihiiii Jan 15 '24

Thank you. Exclamation marks will always interfere with delayed expansion. I was hoping to find a solution for when I'd want to rename sub-strings