Skip to main content

How to Trim Trailing Spaces from a String in Batch Script

Trailing whitespace (spaces or tabs at the end of a string) can be a frustrating source of bugs in scripts. These characters are invisible, but they can cause string comparisons to fail, break file paths, or result in misaligned output. Cleaning this whitespace is a common data sanitization step. Windows Batch has no built-in RTRIM() or TRIMEND() function, so we must rely on a scripted solution.

This guide will teach you the traditional "pure-batch" method, which uses a loop to remove trailing spaces one by one. More importantly, it will demonstrate the vastly simpler and more robust modern approach using a PowerShell one-liner, which is the recommended method for its efficiency and readability.

The Challenge: No Native RTRIM() Function

The cmd.exe interpreter does not provide a single command to trim whitespace from the end of a string. Standard string replacement (%VAR: =%) is not suitable because it would remove all spaces, not just the ones at the end. This means we must build the logic manually, character by character.

The Core Method (Pure Batch): The Character-by-Character Loop

This method is entirely self-contained but is also slow and verbose. It is a good demonstration of advanced batch scripting.

The logic:

  1. Create a subroutine that takes the name of a variable as input.
  2. Inside the subroutine, start a loop.
  3. In each iteration, check if the last character of the string is a space.
  4. If it is, "slice" the string to remove that last character.
  5. Repeat the loop until the last character is no longer a space.

For any modern Windows system, a PowerShell one-liner is a much cleaner and faster solution. It has built-in string methods specifically for this purpose.

Syntax: powershell -Command "' Your String Here '.TrimEnd()"

  • .TrimEnd(): This string method removes all whitespace characters (spaces, tabs, etc.) from the end of the string.
  • .TrimStart(): Similarly removes whitespace from the beginning.
  • .Trim(): Removes whitespace from both the beginning and the end.

This is the recommended approach for its simplicity and power.

Basic Example: Trimming a String

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

Method 1: Pure Batch Script

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

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

CALL :RTrim MyString

ECHO Batch Method Result: "[!MyString!]"
GOTO :End

REM --- Subroutine to trim trailing spaces ---
:RTrim
SET "str=!%1!"
:RTrimLoop
IF "!str:~-1!"==" " (
SET "str=!str:~0,-1!"
GOTO :RTrimLoop
)
SET "%1=%str%"
GOTO :EOF

:End
ENDLOCAL

Output:

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

Method 2: PowerShell Script

@ECHO OFF
SET "MyString=This is a test. "
SET "TrimmedString="

FOR /F "delims=" %%V IN (
'powershell -Command "'%MyString%'.TrimEnd()" '
) DO (
SET "TrimmedString=%%V"
)

ECHO Original string: "[%MyString%]"
ECHO PowerShell Method Result: "[%TrimmedString%]"

Output:

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

How the pure batch script works

  • SETLOCAL ENABLEDELAYEDEXPANSION: Essential for the subroutine to work with the string's changing value.
  • CALL :RTrim MyString: Calls the subroutine, passing the name of the variable to be trimmed.
  • :RTrimLoop: The start of the loop.
  • !str:~-1!: This is the key. The substring syntax ~-1 gets the last character of the string.
  • IF "!str:~-1!"==" ": The condition checks if that last character is a space.
  • SET "str=!str:~0,-1!": If it is a space, this "slices" the string, keeping everything from the beginning (0) up to the next-to-last character (-1), effectively removing the last character.
  • GOTO :RTrimLoop: The loop repeats until the last character is not a space.
  • SET "%1=%str%": This sets the original variable (whose name was passed in as %1) to the final, trimmed value.

Common Pitfalls and How to Solve Them

Problem: What About Leading Spaces?

The pure-batch :RTrim subroutine only removes trailing spaces. It will not touch any spaces at the beginning of the string. While you could write a similar :LTrim function, it becomes very complex.

Solution: Use PowerShell. The .Trim() method handles both leading and trailing whitespace in one simple command.

powershell -Command "'  My String   '.Trim()"

Problem: Performance on Long Strings

The pure-batch loop is very inefficient. It has to re-evaluate and re-slice the string for every single space it removes. If a string has 1,000 trailing spaces, the loop will run 1,000 times.

Solution: Use the PowerShell method. It is a highly optimized, compiled function that runs almost instantly, regardless of the number of spaces.

Practical Example: Cleaning User Input for Comparison

This is a classic use case. A user might accidentally type a space after their name or password. Trimming the input ensures your comparisons work correctly.

@ECHO OFF
SETLOCAL
SET "CorrectPassword=MySecret"

:Prompt
SET "UserInput="
SET /P "UserInput=Enter the password: "

REM --- Trim leading and trailing whitespace using PowerShell ---
SET "TrimmedInput="
FOR /F "delims=" %%V IN ('powershell -Command "'%UserInput%'.Trim()"') DO (
SET "TrimmedInput=%%V"
)

REM --- Now perform a clean, reliable comparison ---
IF "%TrimmedInput%"=="%CorrectPassword%" (
ECHO [SUCCESS] Access granted.
) ELSE (
ECHO [FAILURE] Incorrect password.
ECHO.
GOTO :Prompt
)
ENDLOCAL

Conclusion

While you can trim trailing spaces in a pure batch script, the method is a good example of a task that is better suited for a more powerful tool.

  • The pure-batch character loop is a functional, self-contained solution but is slow and complex to write and maintain.
  • The PowerShell .TrimEnd() (or .Trim()) method is the overwhelmingly recommended best practice. It is faster, more readable, handles all types of whitespace, and can easily manage both leading and trailing spaces.

For any script that requires cleaning string input, the PowerShell one-liner is the most professional and efficient choice.