1

Remove trailing spaces from a file using Windows batch? and How to remove trailing and leading whitespace for user-provided input in a batch file? seem to be similar questions, but I can't get any of the answers to work.

I have a text file, say C:\Users\%username%\Desktop\sometext.txt that has a long list of numbers, some with trailing whitespace. How can I loop through and remove the whitespace at the end of each line? I'd like to do this all in batch. It'll be in a file with some other batch commands in it.

Community
  • 1
  • 1
Michael
  • 356
  • 2
  • 4
  • 12
  • does it have to be a batch file ? Do you deploy your "solution" to a lot of machines and want the least of dependencies ? If not try to get something more "modern". I assume you are on any Windows >= XP. Use powershell for that or windows scripting host, they can be called from your already existing batch. – Marged May 27 '15 at 23:42
  • 1
    Can you be more specific about what in the other answers didn't work for you? – skrrgwasme May 28 '15 at 00:22

1 Answers1

3

Regrettably, you don't show us an example from your file, so we're left to assume from your desription.

Assuming your file is something like

1
22
3
64

where some of the lines have trailing spaces, then

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
(
FOR /f "usebackq" %%a IN (q30594509.txt) DO (
 SET /a num=%%a
 ECHO(!num!
)
)>u:\newfile.txt

GOTO :EOF

I used a file named q30594509.txt containing the above data for my testing.

Produces u:\newfile.txt

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • After I removed the "u:\" as I don't have a "u" drive, this code gave me a "missing operator" error. – gornvix Aug 27 '15 at 18:19
  • @tyebillion : If you simply removed the 'u:\' then this should have created the `newfile.txt` file in your current directory. You should be able to replace `u:\` with any other path to select a different drive/path (but must be `"quoted"` if the destination contains spaces). The error reported indicates a problem with reproducing the code. Best to copy-and-paste, preferably using a decent editor like editplus. Batch is remarkably sensitive to syntax. Removing the `>u:\newfile.txt` completely should report to the screen. That would be my first port of call. – Magoo Aug 29 '15 at 14:49