How to replace a string for a specific line number

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) {
$linenumbers=$line.LineNumber
$test1=$line.Line.Trim()
$len=$test1.length
if($len -eq 2)
{

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

}

}

 

# remove the “GO” keyword from the file

# Create Sample file
@'
GO
Go places
Let's GO
Go
'@ | Out-File .\mySQL1.txt

# Process
Get-Content .\mySQL1.txt | foreach {
    if ($_.ToLower() -ne 'go') { $_ } # remove lines that are 'go'
} | Out-File .\mySQL2.txt

# Validate
notepad .\mySQL1.txt
notepad .\mySQL2.txt

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.

 

# Create Sample file
@'
GO
Go places
Let's GO
Go
'@ | Out-File .\mySQL1.txt

(Select-String -Path .\mySQL1.txt -Pattern '^go$' -NotMatch).Line | Set-Content .\mySQL2.txt