Petter_M
Petter_M

Reputation: 465

Replacing strings in PowerShell: "-"

I know this topic has been widely discussed here, but I am newbie on PowerShell and facing some hurdles to replace a symbol in the table.

In the picture below there some symbols "-" in the numeric column "PRECOMEDIODISTRIBUICAO".

enter image description here

I ran the following code in order to replace such symbols to "0" number:

$file = Import-Csv -Path $file -Delimiter "`t" | 
Select PRECOMEDIODISTRIBUICAO | ForEach {$_ -Replace "\?_", 0} 

But got the following result:

enter image description here

I tried different ways to replace "-" symbol to 0, but got no success. For example: "-", "- ", "\ - " , " - " generated no correction.

Do you have a better idea how to replace such string?

Upvotes: 1

Views: 277

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

Try:

Import-Csv -Path $file -Delimiter "`t" | ForEach {

    $_.PRECOMEDIODISTRIBUICAO = $_.PRECOMEDIODISTRIBUICAO -Replace '-', '0'
    $_
}

Your Select PRECOMEDIODISTRIBUICAO is (should be!) throwing away the other columns, and your replace on $_ -replace is trying to cast the whole object and all its properties into one string, then do the replace, then not save the replaced text anywhere. I don't know what the \? in the regex is doing, but it doesn't look necessary.

Upvotes: 4

Pulkownik
Pulkownik

Reputation: 129

You can dynamically modify strings using code below. 'l' means label and e stand for expression. In the expression you do almost anything with the passed value. In this example replace '-' by 0

Import-Csv -Path $file -Delimiter "`t" |Select @{l="PRECOMEDIODISTRIBUICAO";e={$_.PRECOMEDIODISTRIBUICAO -replace '-', 0}}

Upvotes: 3

Related Questions