How to Remove a Trailing Space in a Batch Variable (10 Steps)by Mike Wallace
Batch files are executable scripts that issue a series of DOS or Windows commands. They are highly useful in system automation tasks and have other uses as well. For example, you can use a batch file to remove all of the trailing "whitespace" characters from a variable. Trailing white spaces occur when you press the space bar too many times after entering a value for a variable. You can save space in memory by removing these unnecessary white spaces, because your variable will contain fewer characters.
Double-click on "My Computer." Double-click on the C: drive to open it.
Right-click anywhere in the C: drive to bring up a context menu. Select "New/Folder" from the context menu to create a folder on the root of the C: drive.
Double-click on the new folder to enter it.
Right-click anywhere in the new folder, and select "New/Text File" to create a blank text file. Name this file "whitespaces.bat."
Right-click "whitespaces.bat" and select "Edit." The default text editor for your system opens the file.
Write the following variable declaration at the top of the text editor. This declaration creates a string of text with a lot of trailing "whitespace" characters. The "&rem" symbol marks the end of the string. set var=Wasted Space: &rem
Write the following to print out the value of the text string: echo."%var%"
Write the following "for" loop structure to remove only the trailing "whitespace" characters. A "for" loop works by reiterating the same instructions a set number of times (in this case, 32). Each iteration looks at one character in the variable and checks to see if it is a trailing "whitespace" or not. If it is, it is deleted. for /l %%a in (1,1,31) do if "!var:~-1!"==" " set var=!var:~0,-1!
Write the following to print out the value of the text string again: echo."%var%"
Double-click on "whitespaces.bat" to execute the script. The output looks like this: "Wasted Space: " "Wasted Space:"