I have the following hashtable:
$lookupTable = @{
"^XXX"="123";
"^YYY"="456";
"cat"="dog"
}
I'm performing a bulk find & replace operation in files as such:
Foreach-Object {
$file = $_
Write-Host "$file"
(Get-Content -Path $file) | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
$line = $line -replace "$_.Name", "$_.Value"
}
$line
} | Set-Content -Path $file
}
You'll notice I have an anchor/caret (^
) on the first two pairs of the hashtable. This is because I want to perform a regex on these so they only match if they are at the beginning of the line. For the third set ("cat"="dog"
) I want to match anywhere (no regular expressions). Unfortunatley, it seems to be taking the ^
literally and is not finding matches nor doing a regex evaluation. I tried defining the regex like below and it works for the first two sets ("XXX"="123"
& "YYY"="456"
), but it won't work for the third set ("cat"="dog"
) as I need to find cat
anywhere in the file, not just at the beginning of the line:
$line = $line -replace "^$($_.Name)", "$($_.Value)"
How can I accomplish this? Thank you very much.