How to remove white space using powershell in multiple text file in the same folder?

Viewed 37

folder name is: c:\home\alltext\

inside has: 2 text files with different names(each text contents extra whitespace that I want to trim)

   text1.txt
   text2.txt

I don't want to use notepad++ and do one by one text.txt if I have more than 2 command.

I tried PowerShell it returns both text1 and text2 together in same one text.txt.

How can I trim them in one command and return individual txt? This is my command:

(get-content c:\home\alltext\*.txt).trim() -ne '' | Set-content c:\home\alltext\*.txt
1 Answers

You need to process the input files one by one:

Get-ChildItem c:\home\alltext*.txt | ForEach-Object {
  Set-Content -LiteralPath $_.FullName -Value (($_ | Get-Content).Trim() -ne '')
}

Note that PowerShell never preserves the original character encoding when reading text files, so you may have to use the -Encoding parameter with Set-Content.


As for what you tried:

(get-content c:\home\alltext*.txt).trim() -ne '' streams the non-blank lines of all files matching wildcard expression c:\home\alltext*.txt, across file boundaries.

Perhaps surprisingly, not only does Set-Content's (positionally implied) -Path parameter accept wildcard expressions too, it writes the same content (the stringified versions of whatever input it receives) to whatever files happen to match that wildcard expression.

This problematic behavior is discussed in GitHub issue #6729; unfortunately, it was decided to retain the current behavior.

Related