How to replace a string for a specific line number

Welcome Forums General PowerShell Q&A How to replace a string for a specific line number

Viewing 2 reply threads
  • Author
    • #283423
      Topics: 1
      Replies: 0
      Points: 12
      Rank: Member

      I have few SQL script files and I am trying to remove the “GO” keyword from the files. unfortunately, there are many other words matching the search criteria and I do not want to replace them.

      I want to replace the “GO” word only in those lines wherein the line does not have any other words except “GO”. I am able to find the line numbers where I have to do the changes but not sure how to make the changes in files.


      $FILEFOLDER =gc “c:\test.sql”

      $linenumber= $FILEFOLDER | select-string “GO”

      foreach($line in $linenumber) {
      if($len -eq 2)

      $contentUpdate = $FILEFOLDER[$linenumbers] -replace “GO=”,”GO=$output”
      Set-Content $NEWPATH $contentUpdate




    • #283435
      Topics: 12
      Replies: 547
      Points: 1,345
      Helping Hand
      Rank: Community Hero
    • #283447
      Topics: 4
      Replies: 422
      Points: 734
      Helping Hand
      Rank: Major Contributor

      Another method using Select-String.  Here we use a regular expression with the start of string (^) and end of string ($) anchors to get an exact match on the line.  We output all lines that don’t match to another file.


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