Reputation: 21
I am trying to replace multiple strings in all files within a folder. The problem is that -replace operator does not take into account the exact words that I need to replace for example:
I need to replace strings:
Now when I run my script it replaces the RUN strings into Run which is good, but it replaces also RUNMODAL into RunMODAL and it does not take into account my second condition. Is there any way to specify that only exact matches should be taken into account or at least for each replace I'd specify the number of characters to be taken into consideration when replacing a particular string?
$AllFiles = Get-ChildItem $FilePath
foreach ($file in $AllFiles) {
(Get-Content $file.PSPath) | ForEach {
$_ -creplace 'RUN', 'Run' `
-creplace 'RUNMODAL', 'RunModal'
} | Set-Content $file.PSPath
}
Edit:
Maybe a better example would be:
Even if I switch these to I would either get NEWfield or Newfield and I need NewField.
Upvotes: 0
Views: 1722
Reputation: 21
I did find also another solution which is:
foreach ($file in $AllFiles)
{
(Get-Content $file.PSPath) | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -like $_.Key)
{
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content $file.PSPath
}
I will try yours as well. Thanks!
Upvotes: 0
Reputation: 200523
Use word boundaries (\b
) in your search strings to ensure that you're replacing only complete words. And you don't need a nested loop. The replacement operators can be used directly on lists.
Get-ChildItem $FilePath | ForEach-Object {
(Get-Content $_.FullName) -creplace '\bRUN\b', 'Run' `
-creplace '\bRUNMODAL\b', 'RunModal' `
-creplace '\bFIELD\b', 'NewField' |
Set-Content $_.FullName
}
Upvotes: 1
Reputation: 1263
$AllFiles = Get-ChildItem $FilePath
(Get-Content $file.PSPath) |
ForEach {
$_ -creplace 'RUNMODAL', 'RunModal' `
-creplace 'RUN', 'Run'
} | Set-Content $file.PSPath
Upvotes: 0