How to remove newlines from a text file with batch or PowerShell


Essentially, I want to read from file.txt with contents

and write to newfile.txt so that it will have contents

I need to do this on a Windows computer on which I do not have install permissions.

I tried

and I tried using PowerShell statements (I cannot run PowerShell scripts) instead of the CMD-style for loop.

but both produce an empty file.
Is there a way to do this?


Get-Content returns the content of a file as an array of lines with the line breaks already removed, so all you need to do (in PowerShell) is to join the lines and write the result back to a file:

Not recommended, but if you must do this in batch you need something like this:

Note that delayed expansion is required for this to work. Without it %row% in the loop body would be expanded at parse time (when the variable is still empty), so you’ll end up with just the last line from the input file in the variable after the loop completes. With delayed expansion enabled (and using !row! instead of %row%) the variable is expanded at run time, i.e. during the loop iterations as one would normally expect.

For further information on delayed expansion see Raymond Chen’s blog.


How to remove newlines from a text file with batch or PowerShell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply