rcubefather
rcubefather

Reputation: 1564

How to search for a string and replace entire line using powershell? (If string NOT matched, need to create a new line with the content)

Sample.txt:

SQL.test = True
wer.vul = 1
temp_RTE = False
user_admin = no

In the above text file, I want to search for a string "test" and replace entire line with "SQL.test = False" using Windows Powershell script. If "test" text is not matched, need to add "SQL.test = False" line to that file.

I have tried this. But I am unable to solve.

Please guide me how to achieve this.

Upvotes: 0

Views: 3442

Answers (3)

Micky Balladelli
Micky Balladelli

Reputation: 9991

One way to do it is as follows:

$text = 'test'
$found = $false
$infile = '.\a.txt'
$outfile = '.\b.txt'
Get-Content -Path $infile | % { 
    if ($_ -match $text)
    {
        $found = $true
        "SQL.test = False"
    }
    else
    {
        $_
    }
} | Out-File -filepath $outfile
if (!$found)
{
    "SQL.test = False" |Out-File -filepath $outfile -Append
}

This can be optimized further, I'm sure.

Basically what this does is use Get-Content to retrieve each line in the text file, and pipe them to Select-String. If the text is found, the line is changed, if not, the original line is returned. If the text is not found, then it's appended.

If the text is found the output is:

SQL.test = False
wer.vul = 1 
temp_RTE = False 
user_admin = no 

else

wer.vul = 1 
temp_RTE = False 
user_admin = no 
SQL.test = False

Upvotes: 1

autosvet
autosvet

Reputation: 880

I think that this should work for you :)

# Get content from the original file
$TXT = Get-Content "C:\temp\New Text Document.txt"
#Path to new file
$NewTXT="C:\temp\newTxt.txt"
$i=0
$TXT|ForEach-Object {
    if ($_ -match "test")
        {($_ -replace $_,"SQL.test = False") | Out-File $NewTXT -Append
        $i++ #increment}
      else
        {$_ | Out-File $NewTXT -Append}
}

If ($i -eq 0) #if $i=0 no "test" found, need to add new line "SQL.test = False"
    {"SQL.test = False" | Out-File $NewTXT -Append}

Upvotes: 0

blabb
blabb

Reputation: 9007

$c = gc .\test.txt
$c | %{ if ( $_ -match "test") { "SQL.test = False" } else {"SQL.test = True"} }

will output

SQL.test = False
SQL.test = True
SQL.test = True
SQL.test = True

for input file

SQL.test = True
wer.vul = 1
temp_RTE = False
user_admin = no

if you meant add "sqlxxxx" to that line simply use the concat + operator

$c | %{ if ( $_ -match "test") { "SQL.test = False" } else {$_ + " SQL.test = True"} }

will output

SQL.test = False
wer.vul = 1 SQL.test = True
temp_RTE = False SQL.test = True
user_admin = no SQL.test = True

Upvotes: 0

Related Questions