Replace string question

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 1 year, 11 months ago.

  • Author
    Posts
  • #21389
    Profile photo of ATG
    ATG
    Participant

    I would like to replace all the number on the left side of the underscore with blank space:
    12_
    123_
    1_
    I am using the following code and it does not work; any help is appreciated.
    (get-content D:\Temp\Test1.txt) | foreach-object {$_ -replace '*_', ' '} | set-content D:\Temp\Test1.txt

  • #21390
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Are you trying to replace any number of characters with a single blank space, or do you want a space for each of the characters that are being taken out? Should the underscore be left in, or taken out with the numbers?

  • #21392
    Profile photo of ATG
    ATG
    Participant

    Just trying to replace any number or character on the left side of the underscore; I am trying to use the wild card *_; but it does not work.

  • #21395
    Profile photo of ATG
    ATG
    Participant

    Sorry if I did not answer your question; the underscore should be left in

  • #21396
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    PowerShell's -replace operator uses regular expressions. You something in front of your * quantifier (perhaps a ., to match any character, but that would depend on whether the lines can have multiple underscores, and what you want the behavior to be if they do), and be sure to keep the underscore. For example:

    (get-content D:\Temp\Test1.txt) | foreach-object {$_ -replace '.*_', ' _'} | set-content D:\Temp\Test1.txt
    

You must be logged in to reply to this topic.