35

How to remove spaces (not replace with underscores) from several thousand files in bulk in Windows? Can I do this from the DOS command?

Currently:

file one.mp3
file two.mp3

All files need to become:

fileone.mp3
filetwo.mp3
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406

9 Answers9

93

Here is a script that can efficiently bulk rename files, stripping all spaces from the name.

:renameNoSpace  [/R]  [FolderPath]
@echo off
setlocal disableDelayedExpansion
if /i "%~1"=="/R" (
  set "forOption=%~1 %2"
  set "inPath="
) else (
  set "forOption="
  if "%~1" neq "" (set "inPath=%~1\") else set "inPath="
)
for %forOption% %%F in ("%inPath%* *") do (
  if /i "%~f0" neq "%%~fF" (
    set "folder=%%~dpF"
    set "file=%%~nxF"
    setlocal enableDelayedExpansion
    echo ren "!folder!!file!" "!file: =!"
    ren "!folder!!file!" "!file: =!"
    endlocal
  )
)

Assume the script is called renameNoSpace.bat

renameNoSpace : (no arguments) Renames files in the current directory

renameNoSpace /R : Renames files in the folder tree rooted at the current directory

renameNoSpace myFolder : Renames files in the "myFolder" directory found in the current directory.

renameNoSpace "c:\my folder\" : Renames files in the specified path. Quotes are used because path contains a space.

renameNoSpace /R c:\ : Renames all files on the C: drive.

dbenham
  • 127,446
  • 28
  • 251
  • 390
  • 1
    Shouldn't the argument be `/R` and not `\R` ? – Mel May 13 '16 at 20:08
  • 1
    @Mel - Yes - all fixed. Thanks. I also renamed the script to something sensible. I had in mind both "renameStrip", and "renameNoSpace", but my brain short circuited and wrote "renameNoStrip". – dbenham May 13 '16 at 20:50
  • 1
    Just came here to say Microsoft needs to add this to their next version of Windows. – xhermit Nov 06 '17 at 15:00
  • Why are there two asterisks in ("%inPath%* \*") ? I'm not fluent with the language, but would think it means everything in inPath, and additionally everything in the current directory. I changed it to ("%inPath%*.myext) and it works. – Peter Feb 04 '19 at 02:12
  • 2
    @Peter - No, it is a single path, and the `* *` (asterisk space asterisk) represents a file name with at least one space. It isn't necessary, but it optimizes the script so that it does not waste time "renaming" files that don't have a space. – dbenham Feb 04 '19 at 04:43
  • @dbenham - Great. I need to modify only names of a certain extension. This makes ("%inPath%* *.myext"). And I need to change space to something else, say to a caret, this makes the rename line: ren "!folder!!file!" "!file: =^!" . It works also with +. Caret seems to be an escape letter, but not in this situation. – Peter Feb 05 '19 at 07:08
  • For anyone who had the same question as I did, simply save the file anywhere. Then double click it to work. I saved it in the folder I need to use it and double clicking renamed everything. Probably best not to put it in C I'd assume or at least edit the above first. – Eoin Sep 28 '19 at 14:56
  • I'm having a problem getting the `/R` to execute. New to the batch language but I thought by including `/R` in the argument, the code would cycle through the subfolders and change the file names within. I can't seem to get this to execute correctly. Renames all files in the active folder correctly but not the subfolders. Am I missing something? – Reece Edwards Mar 24 '20 at 16:52
30

In Windows:

  1. Open a Command Prompt.
  2. Go to the folder with the cd command (eg.: cd "paht of your folder").
  3. Open a powershell by typing: powershell
  4. Then input this: get-childitem *.mp3 | foreach {rename-item $_ $_.name.replace(" ","")}
Javiers
  • 351
  • 3
  • 7
13

Create a powershell file - *.ps1 extension

Write this code:

dir |
Where-Object { $_.name.Contains(" ") } |
Rename-Item -NewName { $_.name -replace " ","" }

save, then right click -> run with powershell

Howli
  • 12,291
  • 19
  • 47
  • 72
bogudoby
  • 131
  • 1
  • 3
  • this failed for me because i think the dir has spaces in it too and dir command doesnt get there, i tried other codes with get children, it works from a powershell command line in the directory, so does... the same command with the where line. thanks – bandybabboon Sep 22 '15 at 07:50
  • It's working for me. How to rename all subfolder also? – sabithkumar Feb 26 '22 at 09:55
7

Open Powershell in windows and then type the following command after navigating to the folder where you want to rename the files

get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace(" ", "") }

Let's Analyze it:

get-childitem *.mp3 This lists all files whose names end with .mp3. They are then piped to the next command with the | operator.

foreach { rename-item $_ $_.Name.Replace(" ", "") }

This replaces all instances of " " (white space in this case || this is the instance which is to be replaced) with nothing, denoted by "", effectively wiping the word from all the files in the directory.

You could also modify get-childitem *.mp3 to get-childitem – that would rename all the files in the directory, not just files whose names end with .mp3.

** Note **

If you do not like the above method there is a awesome software named Bulk Rename Utility. I used this software personally and you can get many tuts on youtube how to use it.

Sachin
  • 1,206
  • 12
  • 13
4

You can write a simple script that does this for one file/directory, e.g.:

@echo off
setlocal enableextensions enabledelayedexpansion

set "ARG=%~1"
ren "%ARG%" "%ARG: =%"

...and then if you'd like, run it over all the files and/or directories you care about. For instance, if you create the above script as myrenamingscript.cmd, you can run it over all non-dir files in the current dir by running:

for %f in (*) do @myrenamingscript.cmd "%~f"
reuben
  • 3,360
  • 23
  • 28
  • okay, so i have created a file name called `myrenamingscript.cmd` and in it i have copy the above scrip and save it as .cmd and then run it (double click it.?), i did not understand your last part where you have said to use `for....` – Nick Kahn Jun 30 '12 at 00:32
  • The script I provided renames one given file or directory to the same name, but with spaces removed. If you want to do this for all the files in a given directory, you'll need to run the script over all the files in the directory. The last comment is a way to do that. – reuben Jun 30 '12 at 01:32
4
@echo off
setlocal enableextensions enabledelayedexpansion

for %%f in (*.*) do (
set ARG=%%~nxf
rename "%%f" !ARG: =!
)
pathe3
  • 348
  • 2
  • 7
3

Since programmatically renaming files is risky (potentially destructive if you get it wrong), I would use a tool with a dry run mode built specifically for bulk renaming, e.g. renamer.

This command strips out the whitespace from all files in the current directory:

$ renamer --find "/\s/g" --dry-run *

Dry run

✔︎ file one.mp3 → fileone.mp3
✔︎ file two.mp3 → filetwo.mp3

Rename complete: 2 of 2 files renamed.

Plenty more renamer usage examples here.

Lloyd
  • 8,204
  • 2
  • 38
  • 53
0

The problem i have faced is that there is a possibility that there is already a file with the name you try to give to the new file (eg if there are 2 files in the folder named "file one.txt" and "file_one.txt" when you try to replace the spaces with underscores, one file will replace the other). So I made this script that checks if the new name already exists and if so places a number at the end of the file name (adds 1 to the number until there is no other file with that name). Instructions about what to change are at the top (commended out lines). Do not store the batch file in the same folder you have the files to be renamed if you use *.* option. I hope this helps.

@echo off

REM Instructions
REM This script repaces spaces from file names with underscores. 
REM If you want to just remove the spaces uncomment lines 30 and 52 and comment out the lines 29 and 51. 
REM set the following parameters. 
REM pb is the folder containing the files we want to rename (fullpath)
REM tm is a temporary folder that will be created and deleted. Just put a folder that does not exist and is not used by anything else (fullpath).
REM all is the file type you want to raname. E.g. *.* for every file, *.txt for TXTs, *.pdf for PDFs etc 
REM you don't have to change anything else

set pb=<folder containing the files to rename>
set tm=<a temp folder that does not exist>
set all=*.*

set pa=%pb%%all%

setlocal EnableDelayedExpansion

cd /d %pa%

set /a count=1

if not exist %tm% mkdir %tm%

for /f %%F in (%pa%) do (

    set name=%%~nF
    set name2=!name: =_!
    REM set name2=!name: =!
    set name3=!name2!%%~xF

    if !name2! == %%~nF ( 
        move /y %%~dpF\!name3! %tm%\ >nul
    ) else (
            if not exist %%~dpF\!name3! ( 
                if not exist %tm%\!name3! (
                    ren "%%F" "!name3!" 
                    move /y %%~dpF\!name3! %tm%\ >nul
                )
        )   
    ) 

)

:rename

for /f %%F in (%pa%) do (

    set name=%%~nF
    set name2=!name: =_!
    REM set name2=!name: =!
    set name4=!name2!%count%
    set name3=!name4!%%~xF

    if !name2! == %%~nF ( 
        move /y %%~dpF\!name3! %tm%\ >nul
    ) else (
            if not exist %%~dpF\!name3! ( 
                if not exist %tm%\!name3! (
                    ren "%%F" "!name3!" 
                    move /y %%~dpF\!name3! %tm%\ >nul
                )
        )   
    ) 

)

set /a count = %count% + 1

set /a loop = 0

for %%F in (%pa%) do (set /a loop = 1)

if %loop% equ 1 goto rename

move /y %tm%\%all% %pb% >nul

rmdir /s /q %tm%
Mike_Gre
  • 81
  • 1
  • 3
0

Just copy paste this to batch-file and save as c:\myfolder\r.bat

setlocal EnableDelayedExpansion
@echo off &cls
set p=%*
set p=!p: =!
set p=!p:^(=!
set p=!p:^)=!
set p=!p:^[=!
set p=!p:^]=!
set p=!p:^$=!
set p=!p:^&=!
set p=!p:^@=!
set p=!p:^;=!
set p=!p:^:=!
set p=!p:^,=!
set p=!p:^#=!
set p=!p:^_=!
set p=!p:^-=!
set e=%p:~-4%
ren "%*" %time:~6,2%%time:~9,2%%e%
exit

Add a registry ket at

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\#myRENAME]
@=""

[HKEY_CLASSES_ROOT\*\shell\#myRENAME\command]
@="c:\myfolder\r.bat \"%1\""

done, now select files & just right-click select myRENAME all the files will be renamed instantly.

s1i2v3a
  • 29
  • 8
  • Ouch - check your logic! (Also, file extensions are not always three letters - think of `.html` or `.xlsx` etc.) – Stephan Nov 05 '21 at 13:54