# Removing Spaces From The End of Batch Variables



## allenfw91 (Nov 7, 2011)

I am creating a batch file that uses user input to set a variable, writes that variable to a file after they hit Enter when they're done inputting data, then uses the file to set the variable value during later runs of the program so the user doesn't have to enter it each time. The problem is that when the variable is entered into the file a space is put at the end, which causes errors when the variable is called later on in the program. Going into the file and manually removing the space at the end fixes the problem. 

The syntax for this is as follows:


```
SET /P workingdir=Please enter the directory you wish to extract audio to then press Enter: 
echo %workingdir% > vars\WORKING_DIR
```
I also tried placing quotes around this line but it did not work:


```
SET /P workingdir="Please enter the directory you wish to extract audio to then press Enter:"
...
```
Is there any way to prevent this space from being entered?


----------



## MPR (Aug 28, 2010)

Look at these:

DOS - String Operations


----------



## allenfw91 (Nov 7, 2011)

I finally figured this out. I used this:


```
SET /P installdir=<vars\INSTALL_DIR
echo [%installdir%]
echo.
for /f "tokens=* delims= " %%A in ('echo %installdir% ') do set installdir=%%A
set installdir=%installdir:~0,-1%
echo [%installdir%]
```
Note that I decided to try putting this when the script reads the variable from the file as opposed to when it writes it to the file. This also lets any amount of space be after the string in the file and the program will still work. The [] around the echoed variable is just to show the spaces. I got the base of this code from here:

Remove leading & trailing spaces from variables... - alt.msdos.batch | Google Groups

Thanks for the help. This was a major thing holding me back with my program.


----------



## Squashman (Apr 14, 2005)

There is a space at the end because you are echoing a space to the file.

```
H:\>echo Squashman >spacetest.txt

H:\>echo Squashman>>spacetest.txt
```


----------



## allenfw91 (Nov 7, 2011)

Thanks for that. I didn't realize that a space between the variable name and the ">" redirection operator echoed a space in the file as well. I feel kind of stupid now for not figuring out that simple thing earlier and going through all this hassle. In my defense though in my DOS and *nix classes we've always been told to put a space in front of and after the redirector.


----------



## Squashman (Apr 14, 2005)

Well now you have something to show all your old teachers.


----------

