The best batch has to offer towards achieving the goal is a combination of for loops to process the string. There is no innate command that can achieve this in a single step.
In a way though, you can make a command to complete the necessary set of commands by a assigning them to a variable as a macro
For example, in the below script the macro completes the necessary steps for this goal by:
- Delimitng the Variables content using
;
- Iterating over the length of the string from end to start - The example assumes a maximum string length of 250 characters; an arbitrary number for the point of the example.
- Remove only trailing spaces using If condition logic and substring modification
- Stop further modification of the variables content by using a true/false switch to flag that the last digit of the string contains a non-space character
Note : Substring modification is used at the point of the the macros expansion to supply the name of the variable to be processed.
@Echo off & Setlocal enableDelayedexpansion
Set "RemTrail=Set "end=0"&(For /F "Tokens=1 Delims=;" %%G in ("^^!$v^^!")Do Set "$V=%%G")&For /L %%i in (250,-1,0)Do (if "^^!$V:~%%i,1^^!"==" " (If not "^^!End^^!"=="1" Set "$V=^^!$V:~0,%%i^^!")Else (If not "^^!$V:~%%i,1^^!"=="" Set "End=1"))"
rem // usage example
Set "string=trail of spaces ; comment string "
Set "string2=uncommented string with trailing spaces and poison chars < & " " | * > "
Echo/[!string!]
Echo/[!string2!]
%RemTrail:$V=String%
%RemTrail:$V=String2%
Echo/[!string!]
Echo/[!string2!]
A slighty modified version that Allows the Delimiter to be modified at expansion, at the expense of returning the modified result in a fixed return variable ($V
) instead of the original variable name:
@Echo off & Setlocal enableDelayedexpansion
Set "RemTrail=For %%n in (1 2)Do if %%n==2 (Set "end=0"&(For /F "Tokens=1 Delims=DLM" %%G in ("^^!$V^^!")Do Set "$V=%%~G")&For /L %%i in (250,-1,0)Do (if "^^!$V:~%%i,1^^!"==" " (If not "^^!End^^!"=="1" Set "$V=^^!$V:~0,%%i^^!")Else (If not "^^!$V:~%%i,1^^!"=="" Set "End=1")))Else Set $V="
rem // usage example
Set "string=trail of spaces ; comment string "
Set "string2=uncommented string with trailing spaces + poison chars < & | * " " > "
Echo/[!string!]
Echo/[!string2!]
%RemTrail:DLM=;%"!string!"
Echo/[!$V!]
%RemTrail:DLM=;%"!string2!"
Echo/[!$V!]
%RemTrail:DLM=+%"!string2!"
Echo/+ Delim example&Echo/[!$V!]