I have a Windows folder which contains a number of subfolders and files. I have noticed that there are several hundred files whose names begin with a blank space, and thus will not copy to a cloud repository (OneDrive). Is there a Windows command or batch file that I could run which would search a folder and its subfolders for any filenames which begin with a blank space, and remove that blank space?
Asked
Active
Viewed 5,160 times
3
-
1Possible duplicate of [Changing white-space on the beginning of a file name](https://stackoverflow.com/questions/46587646/changing-white-space-on-the-beginning-of-a-file-name) – Dec 27 '18 at 09:50
-
Not an awful question, +1, should be on super user. I found this useful – person27 Jul 27 '19 at 18:01
2 Answers
5
A batch file way to do this is as follows:
@echo off
for /R %%A IN (" *") do (
for /F "tokens=*" %%B IN ("%%~nxA") do (
ren "%%A" "%%B"
)
)
- We loop through all subfolders with
/R
option. - We want to find all files starting with a space, so we specify it in parenthesis (
(" *")
).- For each file found we loop through its name specifying
tokens=*
which means to remove any spaces in front. - So, after that we got:
%%A
=
full path to file with a space in its start
%%B
=
just the filename without spaces- So, we rename them with
ren
command.
- So, we rename them with
(closing parenthesis)
- For each file found we loop through its name specifying
(closing parenthesis)
This can be also run from command line in one line:
for /R %A IN (" *") do @for /F "tokens=*" %B IN ("%~nxA") do @ren "%A" "%B"

double-beep
- 5,031
- 17
- 33
- 41
-
There is a typo in batch file code. It should be "%%~nxA" instead of "%~nxA" – vatavale Jun 10 '20 at 09:56
2
You can run the following in PowerShell, update the path variable to point to your folder.
$path = # Path to folder
$files = Get-ChildItem -Path $path -Recurse
Foreach($file in $files)
{
Rename-Item -Path $file.FullName -NewName ($file.Name).Trim()
}

Dejulia489
- 1,165
- 8
- 14