Welcome › Forums › General PowerShell Q&A › How to replace a string for a specific line number
- This topic has 2 replies, 3 voices, and was last updated 2 weeks, 4 days ago by
Participant.
-
AuthorPosts
-
-
December 31, 2020 at 10:22 am #283423
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}
}
-
December 31, 2020 at 10:46 am #283435PowerShell123456789101112131415161718# remove the “GO” keyword from the file# Create Sample file@'GOGo placesLet's GOGo'@ | Out-File .\mySQL1.txt# ProcessGet-Content .\mySQL1.txt | foreach {if ($_.ToLower() -ne 'go') { $_ } # remove lines that are 'go'} | Out-File .\mySQL2.txt# Validatenotepad .\mySQL1.txtnotepad .\mySQL2.txt
-
December 31, 2020 at 12:17 pm #283447
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.
PowerShell123456789# Create Sample file@'GOGo placesLet's GOGo'@ | Out-File .\mySQL1.txt(Select-String -Path .\mySQL1.txt -Pattern '^go$' -NotMatch).Line | Set-Content .\mySQL2.txt
-
-
AuthorPosts
- You must be logged in to reply to this topic.