Skip to main content

How to Remove All Spaces from a String in Batch Script

Cleaning up strings by removing all whitespace is a common task in scripting, especially when preparing user input to be used as a filename, a variable name, or a key. For example, you might want to convert "My Project File" into "MyProjectFile". While Windows Batch has no dedicated REPLACE() function, it has a simple and highly effective string substitution feature that makes this task easy.

This guide will teach you the fast, "pure-batch" method for removing all space characters from a string. We will also cover the more powerful modern approach using PowerShell, which can handle other types of whitespace like tabs.

The Challenge: No Native REPLACE() Function

The cmd.exe interpreter is a simple shell and lacks advanced, built-in text manipulation functions that are common in other languages. You cannot simply call a REPLACE() function. Instead, we use a special syntax for variable expansion to perform a search-and-replace operation.

The Core Method (Pure Batch): String Substitution

This is the most direct and efficient native batch method. It's a simple, one-line operation that replaces all occurrences of one string with another. To remove spaces, we simply replace them with nothing.

Syntax: SET "MyVar=%MyVar: =%"

This syntax requires Delayed Expansion when used inside a loop or after the variable has been modified within a code block. In those cases, the syntax becomes: SET "MyVar=!MyVar: =!"

For a more robust solution that can handle different types of whitespace, a PowerShell one-liner is the best choice. It's clean, powerful, and easy to integrate into a batch script.

Syntax: powershell -Command "'Your String With Spaces'.Replace(' ', '')"

This command is also more explicit and readable, and can be easily modified to remove other characters.

Basic Example: Removing Spaces from a Sentence

Let's remove all the spaces from the string "This is a test string."

Method 1: Pure Batch Script

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MyString=This is a test string."
ECHO Original string: "!MyString!"

SET "NoSpacesString=!MyString: =!"

ECHO Batch Method Result: "!NoSpacesString!"
ENDLOCAL

Output:

Original string: "This is a test string."
Batch Method Result: "Thisisateststring."

Method 2: PowerShell Script

@ECHO OFF
SET "MyString=This is a test string."
ECHO Original string: "!MyString!"

SET "NoSpacesString="

FOR /F "delims=" %%V IN (
'powershell -Command "'%MyString%'.Replace(' ', '')"'
) DO (
SET "NoSpacesString=%%V"
)

ECHO PowerShell Method Result: %NoSpacesString%

Output (for both methods)

Original string: "This is a test string."
PowerShell Method Result: Thisisateststring.

How the Batch Substitution Trick Works

The syntax !MyString: =! is the key to the pure-batch method. Let's break it down:

  • !MyString ... !: The ! characters indicate delayed expansion of the MyString variable.
  • :: This is the separator that signals the start of a search-and-replace operation.
  • : A single space character. This is the substring we are searching for.
  • =: The assignment operator, separating the "find" part from the "replace" part.
  • (nothing): After the =, we provide the replacement string. Since it is empty, every space that is found will be replaced with nothing, effectively deleting it.

Common Pitfalls and How to Solve Them

Problem: Delayed Expansion is Not Enabled

This is the most common error when using this technique inside a FOR loop or IF block. If you use % instead of !, the variable will be expanded only once when the block is first parsed, and the substitution will not work on values that change inside the block.

An example of script with error:

FOR %%F IN (...) DO (
SET "MyVar=A B C"
SET "MyVar=%MyVar: =%" <-- This will fail to work correctly.
)

Solution: Always Use SETLOCAL ENABLEDELAYEDEXPANSION

Enable delayed expansion at the start of your script or subroutine and use the !MyVar: =! syntax for all string manipulations inside loops and IF blocks.

Problem: Handling Other Whitespace (like Tabs)

The batch substitution trick only removes the standard space character (ASCII 32). It will not remove tabs or other forms of whitespace.

Solution: Use PowerShell

PowerShell's .Replace() method can easily be used to remove tabs as well. In PowerShell, the tab character is represented by `t.

@ECHO OFF
SET "MyString=This has tabs."
SET "CleanString="

FOR /F "delims=" %%V IN (
'powershell -Command "'%MyString%'.Replace(' ', '').Replace('`t', '')"'
) DO (
SET "CleanString=%%V"
)

ECHO Cleaned string: %CleanString%

This demonstrates the superior flexibility of the PowerShell method for handling more complex data.

Practical Example: Creating a "Safe" Filename from a String

A perfect use case for this is to take a descriptive name from user input and convert it into a single-word filename.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "ProjectName="
SET /P "ProjectName=Enter the name for your new project: "

ECHO.
ECHO Original name: "!ProjectName!"

REM Remove all spaces to create a safe name for a folder or file.
SET "SafeName=!ProjectName: =!"

ECHO Safe name for folder: "!SafeName!"
ECHO.

MKDIR "!SafeName!"
ECHO Project folder created.

ENDLOCAL

Example of user interaction:

Enter the name for your new project: My Awesome Project 2023

Original name: "My Awesome Project 2023"
Safe name for folder: "MyAwesomeProject2023"

Project folder created.

Conclusion

Removing spaces from a string is a simple task in batch script thanks to its powerful string substitution feature.

  • The pure-batch method (!MyVar: =!) is extremely fast and effective for removing only standard space characters. It is perfect for simple, well-defined tasks.
  • The PowerShell .Replace() method is the recommended best practice for more robust needs. It is more readable and can easily be extended to handle other characters like tabs, making it a more flexible and powerful choice.