Thursday, March 22, 2012

Trimming Trailing Whitespace in Powershell

I needed to remove the trailing spaces from each line in a text file. I came up with this.

    $lines = (Get-Content $filename);
    $lines |
        ForEach-Object { $_.TrimEnd(); } |
        Out-File $_ -Encoding Ascii;

Notice that I specify the encoding on the Out-File cmdlet. This should be set to whatever the encoding of the file is. If that option is omitted, the file is output as double-byte Unicode which is almost never what you'd want.