I noticed that when I use echo to print something to a file in DOS, a space is appended to the string. I need to print the string without the trailing space. Is there a way to do that, or as a workaround, remove trailing spaces from the file?
3 Answers
If I understood the problem correctly, you wrote the trailing space.
Instead of
echo string > file
use
echo string>file

- 14,264
- 2
- 48
- 57
-
Ha! That's exactly it! Didn't realize that echo would output the exact string after it. Thanks! – Rayne Sep 20 '12 at 03:13
-
4This seems good, but it won’t work. Try this: `echo 1 2 3>file`. If the string happens to end with a number, the redirection will treat it as a pipe channel. You could put it in quotes, but you may not want it in quotes. – Synetech Nov 21 '15 at 16:10
-
8@Synetech `(echo 1 2 3)>file` – bers Mar 22 '17 at 13:16
Assuming you're talking about cmd.exe
rather than the actual (rather outdated) MSDOS, there are a number of ways to do this, the first being:
echo Here is some text>output.txt
but I find that somewhat less than readable since I'm used to being able to clearly delineate 'arguments' on the command line.
Alternatively, there's nothing stopping you from swapping around the order of your command line:
>output.txt echo Here is some text
which will allow you to still separate the arguments whilst not having extraneous spaces put in your output file.
In fact, I've often used this method for blocks of code as well:
>output.txt (
echo hello
echo goodbye
)
which will write both lines to the file. I find it preferable in that case since you know right at the start where the output is going, rather than having to go and look at the end of the code block.

- 854,327
- 234
- 1,573
- 1,953
-
I have found that when echoing from inside a block of code it will sometimes looses the carriage return, and output on a single line. – James K Sep 21 '12 at 01:35
-
I also had trouble with leading spaces, so I used the caret(^) escape: echo ^string1, in the above format. Worked a treat. – will Aug 18 '15 at 03:03
-
`echo Here is some text>output.txt but I find that somewhat less than readable since I'm used to being able to clearly delineate 'arguments' on the command line.` More importantly, if the text ends with a number, it will be treated as pipe channel. The second one seems to work well (I don’t recall seeing that form before). Thanks. – Synetech Nov 21 '15 at 16:15
Some quick searching brought me this link
It seems you have multiple options. If you want to parse the file post-echo using a script, you could consider this VBScript
Do While Not WScript.StdIn.AtEndOfStream
WScript.Echo RTrim(WScript.StdIn.ReadLine)
Loop
which loops, line by line through a file(usually .txt), and performs RTrim, which strips trailing spaces.
Cheers

- 1,999
- 10
- 23
-
The same can be accomplished via batch with a `for /f "tokens=* delims= " %%x in (file.txt) echo %x>file2.txt`. But then why not do it in your original file? – James K Sep 21 '12 at 02:01