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.

Step 1

Double-click on "My Computer." Double-click on the C: drive to open it.

Step 2

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.

Step 3

Double-click on the new folder to enter it.

Step 4

Right-click anywhere in the new folder, and select "New/Text File" to create a blank text file. Name this file "whitespaces.bat."

Step 5

Right-click "whitespaces.bat" and select "Edit." The default text editor for your system opens the file.

Step 6

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

Step 7

Write the following to print out the value of the text string: echo."%var%"

Step 8

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!

Step 9

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:"

References

About the Author

Mike Wallace began writing professionally in 2009. He is currently employed as a software engineer who designs, develops and tests software systems. He holds a Bachelor of Science in computer engineering and a Master of Science in electrical and computer engineering from California State University, Chico.

More Articles

×