Loudone
Loudone

Reputation: 349

how to use regex for each line in a file in powershell

In a file I have the kind of line:

I     have lot         of spaces in      me.

and I replace every space by one space with this powershell code:

$String = "I     have lot         of spaces in      me."
while ($String.Contains("  "))
{
$String = $String -replace "  "," "}

the result is :

I have lot of spaces in me.

I would like to do that for each line in a txt file. could you give me the best way to do that?


Part two:

How can I replace something only when there are more than one whitespace with e.g. ;?

The response will be:

;4828;toto;toto;Ticket;0112APPT

and not :

;4828;toto toto;Ticket;0112APPT

To be clear, I would like replace only two White-Space by the Character ;

Upvotes: 3

Views: 2097

Answers (2)

Paxz
Paxz

Reputation: 3036

Like I said in the comments, this should do it for you (atleast in my test):

Get-Content yourfile.txt | % {$_ -replace '\s+', ' '}

Explanation:

Get-Content - Gets Content from given File

| % - foreach line of the content given from Get-Content

$_ -replace '\s+', ' ' - '\s+' stands for one or more whitespaces


If you want to change the content of the File with the replaced strings you can also pipe it to Set-Content and save it in another file:

Get-Content yourfile.txt | % {$_ -replace '\s+', ' '} | Set-Content yourOutputFile.txt

If you want to write to the same file in the pipe, take a look at: Why you dont do it!


Given your second question to ignore single whitespaces in the regex, this is how you would go if you want to replace more than one whitspace with ;.

This will not replace spots with a single whitespace:

Get-Content yourfile.txt | % {$_ -replace '\s\s+', ';'}

Upvotes: 6

boxdog
boxdog

Reputation: 8432

You can do it like this:

(Get-Content '.\TextDocument.txt' -Raw) -replace ' +', ' '

Note that using \s instead of an actual space in the RegEx is an option, but it will remove not just spaces, but such things as tabs and, more crucially, end of line characters.

Upvotes: 3

Related Questions