Regular expressions allow for lookahead, where you can specify an optional pattern that occurs before your desired match. Using conditional logic, you can exclude unwanted matches with that lookahead.
Code:
'(?optional_pattern)wanted_match'
Replace every "echo ", except those proceeded by "@".
Code:
'(?<!excluded_pattern)wanted_match'
$string -replace '(?<!@)echo ','echo/ '
Your next problem is sloppy constraints. What happens if the word "echo" isn't part of a command, but inside a line being echoed?
Code:
@echo off
if exist filename.txt (
echo File exists
) else (
echo File missing
)
echo Don't echo an echo command
Code:
@echo off
if exist filename.txt (
echo/ File exists
) else (
echo/ File missing
)
echo/ Don't echo/ an echo/ command
To solve this condition, we need to convert Get-Content into an array of individual lines, and then perform a "[regex] .Replace(old_string,new_string,count)" on each line where the count is 1 (only replace the first match).
We should also skip files where there's nothing to replace, instead of overwriting all read files.
Code:
param (
[string]$folderPath = (Get-Location)
)
$regex = [regex]'(?<!@)echo '
$fileList = Get-ChildItem -Path $folderPath -File | where { $_.Extension -in '.bat','.cmd' }
foreach ($file in $fileList.FullName) {
$content = Get-Content -Path $file -Raw
if (($content -match $regex) -eq $true) {
$newContent = @()
foreach ($line in @($content -split "`n")) {
$newContent += $regex.Replace($line,'echo/ ',1)
}
$newContent -join "`n" | Set-Content -NoNewline $file -Force
Write-Host Updated $file
}
}
Code:
@echo off
if exist filename.txt (
echo/ File exists
) else (
echo/ File missing
)
echo/ Don't echo an echo command