Skip to main content

How to Remove a Substring from the End of a String in Batch Script

Removing a specific suffix from a string is a common requirement in scripting, especially when dealing with filenames or typed identifiers. You might need to remove a file extension like .txt, strip a trailing _backup tag from a folder name, or clean up a path by removing a trailing backslash. While batch scripting has no dedicated TrimEnd() function, this can be achieved with a clever FOR loop or a simple IF statement combined with substring extraction.

This guide will teach you the most effective methods for removing a known suffix from a string. You will learn the robust FOR loop pattern for removing file extensions and a more general IF/SET pattern for any kind of suffix.

The Challenge: No Direct TrimEnd() Function

The cmd.exe interpreter does not provide a single command to remove a substring from the end of another. We cannot, for example, do SET MyVar=%MyVar% - ".txt". We must manually check for the suffix's presence and then reconstruct the string without it.

Method 1 (For Filenames): FOR Loop Parameter Expansions

This is the best and simplest method when your string is a filename and the suffix you want to remove is its extension. The FOR command's parameter expansions are designed for this.

The %%~nI modifier is the key: FOR %%I IN ("filename.ext") DO SET "NameOnly=%%~nI"

  • FOR %%I IN ("..."): This loop runs once, with %%I holding the full filename.
  • %%~nI: This special modifier expands %%I to its filename part only, automatically stripping the extension.

Method 2 (General Purpose): IF and Substring Logic

When you need to remove an arbitrary suffix (not just a file extension), you need a more general approach.

The logic:

  1. Define the string and the suffix you want to remove.
  2. Use an IF statement to check if the string ends with the suffix. This is done by extracting the end of the string and comparing it.
  3. If the check is successful, calculate the new length of the string (original length minus suffix length).
  4. Use substring extraction to get the part of the string from the beginning up to the new length.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MyString=Project_Folder_backup"
SET "Suffix=_backup"

REM Check if the string ends with the suffix
IF /I "!MyString:~-7!"=="%Suffix%" (
REM If it does, extract the part of the string before the suffix
SET "NewString=!MyString:~0,-7!"
ECHO Suffix found. New string is: !NewString!
) ELSE (
ECHO Suffix not found. String is unchanged: !MyString!
)
note

This requires you to know the length of the suffix (_backup is 7 characters long) beforehand.

Basic Example: Removing a File Extension

This example uses the highly recommended FOR loop method to get a filename without its extension.

@ECHO OFF
SET "FileName=report.final.docx"
SET "NameWithoutExt="

FOR %%F IN ("%FileName%") DO (
SET "NameWithoutExt=%%~nF"
)

ECHO Original Filename: %FileName%
ECHO Name without Extension: %NameWithoutExt%

In the following output, you see that the %%~nF modifier correctly handles multiple dots in the filename.

Original Filename: report.final.docx
Name without Extension: report.final

Common Pitfalls and How to Solve Them

Problem: The Suffix Might Not Be Present

What happens if you try to remove a suffix that isn't there?

  • FOR loop method (%%~nF): This is safe. If the filename has no extension (e.g., "README"), %%~nF will simply return the full filename. No error occurs.
  • General IF method: The IF check will fail, and your "ELSE" block will be executed. This is also safe and predictable.

Solution: Both standard methods handle this case gracefully. The FOR loop is particularly elegant as it requires no explicit check.

Problem: Case-Sensitivity in Comparisons

The FOR %%~nF method is case-preserving but removes the extension regardless of its case (e.g., it works on .TXT, .txt, and .Txt).

The general IF method, however, requires you to be deliberate. IF "!MyString:~-4!"==".txt" is case-sensitive.

Solution: For the general method, add the /I switch to the IF statement to make the comparison Insensitive to case. IF /I "!MyString:~-4!"==".txt"

Practical Example: Removing a Trailing Backslash

A common cleanup task is to ensure a folder path does not have a trailing backslash. This is a perfect use case for the general IF/SET method.

@ECHO OFF
SETLOCAL
SET "FolderPath1=C:\Users\Admin\Documents\"
SET "FolderPath2=C:\Users\Admin\Documents"

CALL :CleanPath FolderPath1
CALL :CleanPath FolderPath2

ECHO Cleaned Path 1: %FolderPath1%
ECHO Cleaned Path 2: %FolderPath2%
GOTO :EOF


:CleanPath
SETLOCAL ENABLEDELAYEDEXPANSION
SET "FullPath=!%1!"

REM Check if the last character is a backslash.
IF "!FullPath:~-1!"=="\" (
REM If it is, get the substring from the start, excluding the last char.
SET "CleanedPath=!FullPath:~0,-1!"
) ELSE (
SET "CleanedPath=!FullPath!"
)

ENDLOCAL & SET "%1=%CleanedPath%"
GOTO :EOF

Output:

Cleaned Path 1: C:\Users\Admin\Documents
Cleaned Path 2: C:\Users\Admin\Documents

Conclusion

While batch scripting lacks a direct function to remove a suffix, the provided methods are powerful and reliable.

  • For removing a file extension, the FOR loop with the %%~nF modifier is the simplest, most robust, and highly recommended method.
  • For removing any general suffix, the combination of an IF statement and substring extraction (%VAR:~0,-N%) is the standard and effective pattern.

By choosing the right technique for your situation, you can easily and reliably remove any trailing substring to format your data correctly.