技术问询:如何移除文件名及文件夹名的空格?含批量及仅首尾需求
Hey there! Let's tackle your two file/folder renaming needs step by step. I'll cover solutions for both Windows (using PowerShell) and Linux/macOS (using bash) since those are the most common environments.
Windows (PowerShell)
This command will recursively process all files and folders in your current directory, stripping every single space from their names:
Get-ChildItem -Recurse | Rename-Item -NewName { $_.Name -replace '\s', '' }
-Recurse: Ensures we process files and folders inside subdirectories too.-replace '\s', '': Uses regex to replace any whitespace character (spaces, tabs, etc.) with an empty string. If you only want to target regular spaces, use' 'instead of'\s'.
Pro tip: Add -WhatIf at the end first to preview changes without actually renaming anything:
Get-ChildItem -Recurse | Rename-Item -NewName { $_.Name -replace '\s', '' } -WhatIf
If you don't want to process subdirectories, simply omit the -Recurse flag.
Linux/macOS (Bash)
Use this find command with Perl-style rename (standard on most modern systems) to remove all spaces recursively:
find . -depth -name "* *" -execdir rename 's/\s+//g' {} +
-depth: Renames files inside folders before renaming the folders themselves, avoiding broken file paths.'s/\s+//g': Regex pattern that globally replaces one or more whitespace characters with nothing. Use's/ //g'if you only want to target regular spaces.
If your system uses the util-linux version of rename, use this alternative with mv and sed:
find . -depth -name "* *" -execdir bash -c 'mv "$0" "$(echo "$0" | sed "s/ //g")"' {} \;
To limit to the current directory only, add -maxdepth 1 to the find command.
Windows (PowerShell)
This command trims spaces only from the start and end of file/folder names, leaving any internal spaces intact:
Get-ChildItem -Recurse | Rename-Item -NewName { $_.Name -replace '^\s+|\s+$', '' }
^\s+: Matches one or more spaces at the start of the name.\s+$: Matches one or more spaces at the end of the name.|: Acts as an "or" operator, targeting both patterns simultaneously.
Preview changes first with -WhatIf:
Get-ChildItem -Recurse | Rename-Item -NewName { $_.Name -replace '^\s+|\s+$', '' } -WhatIf
Omit -Recurse if you don't need to process subdirectories.
Linux/macOS (Bash)
Use this find command with Perl-style rename to trim leading/trailing spaces:
find . -depth -name "* *" -execdir rename 's/^\s+|\s+$//g' {} +
The regex works exactly like the PowerShell version—only spaces at the very start or end of each name are removed.
For util-linux rename, use this alternative:
find . -depth -name "* *" -execdir bash -c 'mv "$0" "$(echo "$0" | sed "s/^[[:space:]]*//; s/[[:space:]]*$//")"' {} \;
Add -maxdepth 1 to restrict to the current directory.
Quick Safety Note
Always back up your files before running bulk rename commands, just in case something unexpected happens—it's a small step that saves a lot of hassle!
内容的提问来源于stack exchange,提问作者MarcosArispe

