9

I found a find-and-replace text answer from another question.

How do I use PowerShell to remove extra spaces at end of line in a text file?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Swan Lee
  • 93
  • 1
  • 1
  • 3

2 Answers2

25

There are a number of approaches but this one is pretty simple:

$content = Get-Content file.txt
$content | Foreach {$_.TrimEnd()} | Set-Content file.txt

You may need to tweak the Encoding parameter on the Set-Content cmdlet to get the file output in the encoding you want (Unicode, ASCII, UTF8, etc).

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
0

For small files (less than 250 MB) you could use:

$file = "Log20130820"

Get-Content $file  | Foreach {$_.TrimEnd()}  | Set-Content "$file.txt"

For files that are too large, the script would fail with OutOfMemoryException.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ItsMe
  • 1