Question about replacing one specific character in a value

Welcome Forums General PowerShell Q&A Question about replacing one specific character in a value

Viewing 4 reply threads
  • Author
    Posts
    • #220236
      Participant
      Topics: 3
      Replies: 6
      Points: 22
      Rank: Member

      With the following I try to select a pattern like .1;ENM and then I want to replace the dot with a comma.

      Code example

      Get-Content .\import.csv |

      Select-String -pattern “.\d;ENM”

      | ForEach-Object {$_.matches.value -replace ‘.’,’,’}

      I select an object and select the value (which is a string) but the whole value is replaced with the comma so the output I get is ,,,,,, instead of the wanted ,1;ENM. Can anybody point me in the right direction?

       

    • #220239
      Participant
      Topics: 4
      Replies: 2247
      Points: 5,484
      Helping Hand
      Rank: Community MVP

      The dot “.” is a special charachter for regex. So you have to escape it if you want to find a literal one. 😉

      Get-Content .\import.csv |
      Select-String -pattern '\.\d;ENM' | 
      ForEach-Object {$_.matches.value -replace '\.',','}

      When you post code or error messages or sample data or console output format it as code using the code tags “PRE” you find in the text view of the post editor, please. Thanks in advance.

    • #220245
      Participant
      Topics: 5
      Replies: 322
      Points: 445
      Helping Hand
      Rank: Contributor

      Also, you can use parentheses to create a match group then replace.

      Get-Content .\import.csv | ForEach-Object {$_ -replace '(\.)(\d;ENM)',',$2'}
      
    • #220257
      js
      Participant
      Topics: 29
      Replies: 813
      Points: 2,450
      Helping Hand
      Rank: Community Hero

      Do you want to change the whole line?

      (get-content import.csv) -replace '\.',',' | set-content import2.csv

      When in doubt, [regex]::escape

      [regex]::escape('.')
      
      \.
      • This reply was modified 1 month, 2 weeks ago by js.
      • This reply was modified 1 month, 2 weeks ago by js.
    • #220296
      Participant
      Topics: 3
      Replies: 6
      Points: 22
      Rank: Member

      Thank you soo much! Immediate replies, not only the solution but also some explainations and worthwhile background.

      And from a learning point of view, since I really struggled with this and when I read your comments it really makes sense so it is etched in my mind and really learned.

      So thanks community, what a wonderfull forum this is!

Viewing 4 reply threads
  • You must be logged in to reply to this topic.