Reputation: 1
I need to find this pattern, "LogEntry="
, across multiple lines in the following file:
C:\test.conf
And change the line to read: "LogEntry=&MAC="
instead.
The script works fine so far to do that, but if someone runs the script twice it will re-add the same pattern, doubling it up.
I need to find a way to put a check in place to know if the file already has that pattern in it. Could someone please give me a hand with this one ?
Upvotes: 0
Views: 114
Reputation: 201662
Use negative lookahead in your regex e.g.:
'LogEntry=(?!&MAC=)'
That regex will not match the already modified line. Read more about look ahead/behind zero length assertions.
BTW if you have the PowerShell Community Extensions, you can do this edit operatio with a single command:
Edit-File C:\test.conf -Pattern 'LogEntry=(?!&MAC=)' -Replace 'LogEntry=&MAC='
And if you can't use PSCX's Edit-File, here is roughly the equivalent:
$content = Get-Content C:\test.temp
$content | Foreach {$_ -replace 'LogEntry=(?!&MAC=)','LogEntry=&MAC='} | Out-File -Encoding ASCII
I don't know what the file encoding is for your file. You need to know that and use the appropriate encoding on the Out-File
command. If you don't specify the encoding, it defaults to Unicode.
Upvotes: 1