ghfhdfghdfgh
ghfhdfghdfgh

Reputation: 9

Renaming files with spaces and dots in the filename

I'm making a simple *bat file with drag/drop ability for replacing white spaces( ) and dots(.) for underscores(_).

I think this should work, but it doesn't:

@ECHO OFF
setlocal enabledelayedexpansion
FOR %%f IN (%*) DO (
set filename=%%~nj
set filename=!filename:.=_!
set filename=!filename: =_!
if not "!filename!"=="%%~nf" RENAME "%%f" "!filename!%%~xf"
)

Do you know what is going on?

Upvotes: 1

Views: 2669

Answers (2)

Endoro
Endoro

Reputation: 37569

try this:

@ECHO OFF &setlocal

FOR %%f IN (%*) DO (
set "oldname=%%~ff"
set "oldfname=%%~nf"
set "extension=%%~xf"
setlocal enabledelayedexpansion
set "filename=!oldfname:.=_!"
set "filename=!filename: =_!"
if not "!filename!"=="!oldfname!" RENAME "!oldname!" "!filename!!extension!"
endlocal
)

Put the assignment of set in double quotes to protect your code from ugly characters. Set delayed expansion later in the for loop to save exclamation marks and carets in file names.

Upvotes: 2

Christian.K
Christian.K

Reputation: 49250

Your loop variable is %%f but in the first line, where you assign it to filename you use %%j.

Your code should look like this:

@ECHO OFF
setlocal enabledelayedexpansion
FOR %%f IN (%*) DO (

rem corrected-begin
set filename=%%~nf
rem corrected-end

set filename=!filename:.=_!
set filename=!filename: =_!
if not "!filename!"=="%%~nf" RENAME "%%f" "!filename!%%~xf"
)

Also, you might want to make sure you strip eventual quotes consistently. That is, the last line of your loop should read:

if not "!filename!"=="%%~nf" RENAME "%%~f" "!filename!%%~xf"

Then, you should not suppress the directory-part of the files being moved.

if not "!filename!"=="%%~nf" RENAME "%%~dpnxf" "!filename!%%~xf"

Before letting your code loose, you may want to replace that last line with something like:

if not "!filename!"=="%%~nf" ECHO RENAME "%%~f" "!filename!%%~xf" >> "%TEMP%\test.txt"

Then, after your drag n' drop operation inspect "%TEMP%\test.txt" to see if it contains the operations, and on the files, you expected.

For reference, here is the complete file after all changes:

@ECHO OFF
setlocal enabledelayedexpansion
FOR %%f IN (%*) DO (
    set filename=%%~nf
    set filename=!filename:.=_!
    set filename=!filename: =_!
    rem uncomment  for debugging.
    rem if not "!filename!"=="%%~nf" ECHO RENAME "%%~dpnxf" "!filename!%%~xf" >>     "%TEMP%\test.txt"
    rem comment for debugging.
    if not "!filename!"=="%%~nf" RENAME "%%~dpnxf" "!filename!%%~xf"
)

Upvotes: 0

Related Questions