Renaming files with spaces and dots in the filename

拥有回忆 提交于 2020-01-05 07:59:08

问题


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?


回答1:


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.




回答2:


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"
)


来源:https://stackoverflow.com/questions/16712881/renaming-files-with-spaces-and-dots-in-the-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!