How to replace all spaces by underscores in all file names of a folder?

后端 未结 8 2289
鱼传尺愫
鱼传尺愫 2020-12-07 18:50

I\'m trying to rename all the files inside a folder (all .exe files). I want to replace all the spaces with underscores, e.g. qwe qwe qwe asd.exe to qwe_q

相关标签:
8条回答
  • 2020-12-07 19:25

    Simple as:

    set filename=qwe qwe qwe asd.exe
    set filename=%filename: =_%
    
    0 讨论(0)
  • 2020-12-07 19:25

    Based on @Gray answer, I have extending it to replace filenames recursively in all subdirectories.

    File 1: replace.bat

    setlocal enabledelayedexpansion
    
    set "pattern= "
    set "replace=_"
    
    for %%I in (*.ext) do (
        set "file=%%~I"
        ren "%%I" "!file:%pattern%=%replace%!"
    )
    

    File 2: recursive.bat

    for /d /r . %%D in (*) do (
        copy replace.bat "%%D\replace.bat"
        cd "%%D"
        replace.bat
        del replace.bat
        cd..
    )
    

    Files

    • replace.bat contains script to replace space with underscore
    • recursive.bat contains script to do recursion in all subdirectories

    How to use?

    • Save both replace.bat and recursive.bat in same directory.
    • Replace .ext with desired file extension to match (like .mp4) in replace.bat.
    • Double click (run) ONLY recursive.bat file.
    0 讨论(0)
  • 2020-12-07 19:25

    set data=%date:~6,4%%date:~3,2%%date:~0,2%_%time:~0,2%%time:~3,2%%time:~6,2% set data=%data: =0%

    0 讨论(0)
  • 2020-12-07 19:29

    Using forfiles:

    forfiles /m *.exe /C "cmd /e:on /v:on /c set \"Phile=@file\" & if @ISDIR==FALSE ren @file !Phile: =_!"
    

    Add /s after forfiles to recurse through subfolders.

    0 讨论(0)
  • 2020-12-07 19:30

    Save the following 2 commands in a .bat file. It will replace " " with "_" in all files and folders, recursively, starting from the folder where the file is stored.

    forfiles /s /m *.* /C "cmd /e:on /v:on /c set \"Phile=@file\" & if @ISDIR==FALSE ren @file !Phile: =_!"
    forfiles /s /C "cmd /e:on /v:on /c set \"Phile=@file\" & if @ISDIR==TRUE ren @file !Phile: =_!"
    

    Note: First line is doing this for files, and second one is doing this for folders. Each line can be used separately.

    0 讨论(0)
  • 2020-12-07 19:44

    Adapted from here:

    https://stackoverflow.com/a/16129486/2000557

    @echo off
    Setlocal enabledelayedexpansion
    
    Set "Pattern= "
    Set "Replace=_"
    
    For %%a in (*.exe) Do (
        Set "File=%%~a"
        Ren "%%a" "!File:%Pattern%=%Replace%!"
    )
    
    Pause&Exit
    

    Create a batch file (*.bat) with the above contents. Place that batch file in the folder with all the .exe's and it will replace the spaces with underscores when you run it.

    0 讨论(0)
提交回复
热议问题