Read Characters and replace if a match is found

This topic contains 2 replies, has 2 voices, and was last updated by  Suzanne 4 months ago.

  • Author
  • #91645


    I am getting a text file where I need to read the 1st ll positions in each line of the file. If a "-" is found I need to replace that with a ",".

    I do not want to change any other "-" within the file only the 1st one. The "-" can float between position 5 & 9.

    Is there a way to accomplish this

  • #91646

    Don Jones

    One way would be to convert the string to an array of Char (characters), and the enumerate the positions you care about. Regular expressions would also be an approach you could take.

  • #91692


    I think I figured it out. Since I need the very first instance of the "-" to a "," and nothing else...I used this line.

    $content | Foreach-object { $_ -replace '^(.*?)-', '$1,'} | Set-content $file

    It appears to be working and made it very simple.

You must be logged in to reply to this topic.