1

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?

4
  • 1
    -Replace '\-', '0' Commented Jul 20, 2018 at 17:14
  • 3
    If you want to replace the - character, why are you replacing \?_? Commented Jul 20, 2018 at 17:14
  • Please don't post pictures, where text would serve as well. Commented Jul 20, 2018 at 18:58
  • @LotPings Sure! I'll avoid it... Commented Jul 20, 2018 at 19:12

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In case there could be negative numbers, I'd -Replace '^-$','0'
That's weird...the same error persisted even after declaring the column name.
3

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}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.