Read Characters and replace if a match is found

Welcome Forums General PowerShell Q&A Read Characters and replace if a match is found

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
9 months, 4 weeks ago.

  • Author
    Posts
  • #91645

    Participant
    Points: 0
    Rank: Member

    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

    Keymaster
    Points: 1,619
    Helping HandTeam Member
    Rank: Community Hero

    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

    Participant
    Points: 0
    Rank: Member

    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.

The topic ‘Read Characters and replace if a match is found’ is closed to new replies.