Home > Software engineering >  Replace whole string if part of the string is "not correct"
Replace whole string if part of the string is "not correct"

Time:09-08

i need to make a script for "check/replace/add string to the file. The "correct" string is "google.com 44.10.15.9" I have a part of the script for adding the whole line, but i don't know how to make it check other options, If the string would be there but only "google.com" without address or with wrong address. My work looks like this.

$file= 'C:\Users\fialbvoj\Desktop\testPS.txt'
$name=" google.com "
$IP=" 44.10.15.9 "
$line="google.com 44.10.15.9"
$search=(Get-Content $file | Select-String -Pattern 'google.com 44.10.15.9').Matches.Success

if ($search ) {"Success"
} else {
    Add-Content -Path $file -Value $line
}

Thank you in advance. Best Regards

CodePudding user response:

Select-String accepts regular expressions for the -Pattern parameter which allows you to use a regular expression for the IPAddress instead of a literal IP address, e.g.:

 ... |Select-String 'google\.com ((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}'

To replace the any pattern with the "correct string" (aka IP address):

(Get-Content $file) -Replace 'google\.com ((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}', 'google.com 44.10.15.9' |Set-Content $file

Note 1: the parenthesis around (Get-Content $file) are only required if you need to write back to the same file.
Note 2: the backslash in google\.com is required to escape the dot which normally represents any character in a regular expression.

  • Related