MatDDev
MatDDev

Reputation: 21

Replace multiple strings in multiple files

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:

  1. RUN → Run
  2. RUNMODAL → RunModal

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:

  1. FIELD → field
  2. NEWFIELD → NewField

Even if I switch these to I would either get NEWfield or Newfield and I need NewField.

Upvotes: 0

Views: 1722

Answers (3)

MatDDev
MatDDev

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

Ansgar Wiechers
Ansgar Wiechers

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

Nas
Nas

Reputation: 1263

$AllFiles = Get-ChildItem $FilePath

(Get-Content $file.PSPath) |
ForEach {
       $_ -creplace 'RUNMODAL', 'RunModal' `
          -creplace 'RUN', 'Run'
} | Set-Content  $file.PSPath

Upvotes: 0

Related Questions