Replace every empty space the beginning and the end

Hi All. I want to use get-content and -replace to replace empty spaces:

The text file

Line1:abcd

Line2:cdef

       Line3:jukq

Line4:casdj

September 5th, 2014 10:45pm

First of all, this isn't relevant to DPM so would have been more appropriate being posted in http://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverpowershell and potentially have a better chance of being replied to before now.

That said, doing what you're after is fairly straight forward, though the exact method depends on what you're trying to achieve.

If you want to update the existing file c:\input.txt so that same file ends up with the spaces removed, then use :

(Get-Content C:\input.txt) | 
Foreach-Object {$_ -replace " ",""} |
Set-Content C:\input.txt
Alternatively, if you're trying to load those values into a variable ($foo) but with the spaces removed then you can use :
$foo = (Get-Content C:\input.txt) | 
Foreach-Object {$_ -replace " ",""} 

Free Windows Admin Tool Kit Click here and download it now
September 6th, 2014 1:54am

You can use the Trim() method as in:

Set-Content -Path .\spaces.txt -Value  (Get-Content -Path .\spaces.txt).Trim() -Force

September 6th, 2014 5:17am

using {$_ -replace " ",""}  should only take out 1 empty character...

Not sure what makes you think that, but you're wrong. -replace acts on all matches not just the first one, and in the specific case I provided it removes ALL white space before the text. I tested the code I was providing before posting, and my test data includes more than one whitespace character since the OP's example does as well.
Free Windows Admin Tool Kit Click here and download it now
September 6th, 2014 5:37am

the point is I want to replace the space at the beginning of each line

Sorry if I'm being stupid but that's what the code I provided does. If input.txt contains

Line1:abcd
Line2:cdef
       Line3:jukq
Line4:casdj

then the output of that code will be :

Line1:abcd
Line2:cdef
Line3:jukq
Line4:casdj

with the spaces at the beginning removed, which is what I thought you were after.

September 8th, 2014 9:48am

the point is I want to replace the space at the beginning of each line
Free Windows Admin Tool Kit Click here and download it now
September 8th, 2014 10:21pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics