How to use PowerShell to remove space from the end of a line in a text file

I found the text of the answer to search and replace another question.

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

+5
source share
2 answers

There are several approaches, but it is quite simple:

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

You may need to configure the parameter Encodingin the Set-Content cmdlet to get the file in the desired encoding (Unicode, ASCII, UTF8, etc.).

+16
source

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

$file = "Log20130820"

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

For files that are too large, the script will exit with an OutOfMemoryException.

0
source

All Articles