批处理文件将“。”替换为“-”

批处理文件将“。”替换为“-”

我需要保留文件扩展名,并且它需要通过子文件夹来工作。

例如:“File.name.ext”应改为“File-name.ext”

我对 shell 脚本一无所知,所以请在回复中详细说明。我不知道任何开关的含义,甚至不知道如何指定路径。

答案1

我完全同意另一个答案。GUI 批量重命名实用程序将是所以使用起来更容易。但是,为了好玩,我编写了以下批处理文件,该文件应以递归方式重命名当前目录和子目录中的所有文件。并将 . 替换为 - (例如“长文件. .name.ext“ 会变成 ”长文件名称.ext“):

@echo off
setlocal enabledelayedexpansion
for /r %%f in (*.*) do (
    set fn=%%~nf

    REM Remove the echo from the following line to perform the actual renaming!
    if not [!fn!]==[] if not ["%%~nxf"]==["!fn:.=-!%%~xf"] echo ren "%%~f" "!fn:.=-!%%~xf"
)
pause

运行批处理文件一次,然后如果输出看起来令人满意,则通过删除单词echo(第二个实例,而不是第一行)并重新运行文件来执行实际重命名。

答案2

我有点不明白你为什么要费心使用批处理文件。为什么不使用无数个 GUI 重命名工具中的一个,例如:

http://www.beroux.com/english/softwares/renameit/

如果这个游行不能引起你的兴趣,那就看看这个游行吧:

http://www.techsupportalert.com/best-free-rename-utility.htm

答案3

这是我最终测试过的批处理文件版本,它可以满足您的要求。它适用于带或不带文件名或扩展名的文件,但文件名包含%或的文件!引起麻烦

它使用延迟扩展,因此你必须在打开延迟扩展的命令提示符下运行它(简单地运行setlocal /enabledelayedexpansion是行不通的,因为那只会切换它如果已启用;如果在运行命令提示符时未启用它,则它无效)。

您可以通过使用开关打开命令提示符来打开延迟扩展/V:ON,但您也可以从现有的命令提示符中执行此操作,如下面的批处理文件所示。

@echo off

:: This batch file (prints the command to) rename files so that
:: any dots (.) are replaced with dashes (-)
::
:: Note, files with names containing percents (%) and exclamantions (!)
:: will intefere with command-prompt syntax and are not supported, but
:: can be worked around: https://stackoverflow.com/questions/5226793/

:: If this batch-file has no parameters...
if [%1]==[] (
    :: Open a new command-prompt with delayed-expansion enabled and call self
    cmd /v:on /c "%0" +
    :: Quit
    goto :eof
)

:: Recurse through all files in all subdirectories
for /r %%i in (*) do (

    rem (:: cannot be used for comments in a FOR loop)
    rem Check if it has an extension
    if [%%~xi]==[] (
        rem If it has an extension, preserve it
        set RENFN=%%~nxi
    ) else (
        rem Copy the path (and filename)
        set RENFN=%%~ni
        rem Check if it has a filename
        if not [%%~ni]==[] (
            rem If it has a filename, replace dots with dashes
            set RENFN=!RENFN:.=-!
        )
    )

    rem Rename original file
    ren "%%i" "!RENFN!%%~xi"

)

:: Exit spawned shell (no need to use setlocal to wipe out the envvar)
exit

:: Test output:
::
:: C:\t> dir /b/a
::
:: .txt
:: blah
:: file.blah.txt
:: foo.bar.txt
:: super duper. .blah.ttt. omergerd.---.mp4
:: t.bat
::
:: C:\t> t.bat
::
:: ren "C:\t\.txt" ".txt"
:: ren "C:\t\blah" "blah"
:: ren "C:\t\file.blah.txt" "file-blah.txt"
:: ren "C:\t\foo.bar.txt" "foo-bar.txt"
:: ren "C:\t\super duper. .blah.ttt. omergerd.---.mp4" "super duper- -blah-ttt- omergerd----.mp4"
:: ren "C:\t\t.bat" "t.bat"

相关内容