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

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


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:

(Get-Content 'input.txt') -join ' ' | Set-Content 'output.txt'

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

@echo offsetlocal EnableDelayedExpansionset row=for /f %%x in (file.txt) do set "row=!row! %%x">newfile.txt echo %row%

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.


To complement Ansgar Wiechers' helpful answer:

Executing the following command from a batch file / a cmd.exe console window should do what you want:

powershell -command "\"$(Get-Content file.txt)\" > newFile.txt"
  • Note the escaping of embedded " as \", which PowerShell requires when called from the outside (by contrast, PowerShell-internally, ` is the escape character).

  • Enclosing the Get-Content file.txt call - which outputs an array of lines - in a double-quoted string, using subexpression operator $(...), means that the array elements are implicitly joined with a space each.

Note, however, that PowerShell's output-redirection operator, >, creates UTF16-LE ("Unicode") encoded files by default, as does Out-File (at least in Windows PowerShell; the cross-platform PowerShell Core defaults to (BOM-less) UTF-8).

To control the output encoding, use the -Encoding parameter, which you can apply to Out-File or, preferably - knowing that strings are being output - Set-Content.

In Windows PowerShell, note that Set-Content - in contrast with > / Out-File - defaults to the encoding implied by the legacy "ANSI" code page, typically Windows-1252.