What do I have to change here in this code so it could do also subfolders? Or if it is easier to run only through subfolders?
@echo off
setlocal enableDelayedExpansion
for %%F in (*.jpg) do (
set "name=%%F"
ren "!name!" "!name:_=!"
)
This runs ok in current folder it erase in jpg filename character "_", but I don't know how to do it in subfolders, and that is my main goal to do.
It is possible to use a For /R
loop:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /R . %%G In ("*_*.jpg") Do (
Set "name=%%~nxG"
SetLocal EnableDelayedExpansion
If Not Exist "%%~dpG!name:_=!" Ren "%%G" "!name:_=!"
EndLocal
)
I have used a .
character after /R
to signify the current directory as the recursion base, whilst this is not necessary, because the current directory is assumed if no path is provided, it serves as a reminder, the you could include another path there if needed.
Although you could also use a For /F
loop, with the Dir
command:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /F "EOL=? Delims=" %%G In ('Dir /B/S/A:-D "*_*.jpg"') Do (
Set "name=%%~nxG"
SetLocal EnableDelayedExpansion
If Not Exist "%%~dpG!name:_=!" Ren "%%G" "!name:_=!"
EndLocal
)
In this case, if you wanted to use a directory other than the current directory, you can insert it directly in the Dir
glob, e.g. "C:\SomePath\*_*.jpg"
Please note however, in both cases, no attempt has been made to ensure that the remaining string, after removal of the underscores is a valid filename. It is your responsibility to incorporate such a check, if you wish to have robust code in your environment. Additionally no check is included to ensure that short filenames, (8.3), are not matched, so if this could be an issue in your target environments, then you should include modifications or additions to cater for that.