Forum Discussion
Hjb118
Feb 04, 2023Copper Contributor
Replace specific letters and word in a text file
Good Afternoon,
I am trying to create script that will take file, read each line, replace a specific word/letter, then output that line to new file but having trouble replacing the words/letters.
Example text file:
Is this your password <Password>
is this your IP 10.<A>.<X>.1
$filePath = "C:\temp\fileA.txt"
$newFilePath = "C:\temp\fileB.txt"
$configurationData = New-Object System.Collections.Generic.Dictionary"[String,String]"
$configurationData.add("<Password>","blah")
$configurationData.add("<A>","0")
$configurationData.add("<x>","0")
$replacementlist = @("<Password>","<A>","<x>")
foreach($line in [system.IO.File]::Readlines($filePath)){
    foreach($key in $replacementlist)
        {
            $newText = $configurationData.item($key)
            if ($line -match "$key")
            {
                $output = $True
        
                $line -replace "\[$($key)", "$newText" | out-file -filePath $newFilePath -Append
        
                write-output $line
            }
            else
            {
                $output = $false
            }
        } 
  
       if($output -eq $false){
           $line | out-file -filePath $newFilePath -Append
        }
}
When it's trying to replace to words/letters it doesn't find them to replace it.  
Thanks for all help
Hello Hjb118,
You can achieve needed result with one foreach loop:
$filePath = ".\input.txt" $newFilePath = "output.txt" $configurationData = New-Object System.Collections.Generic.Dictionary"[String,String]" $configurationData.add("<Password>","blah") $configurationData.add("<A>","0") $configurationData.add("<x>","0") $replacementlist = @("<Password>","<A>","<x>") $InputData=Get-Content $filePath foreach($key in $replacementlist){ $InputData=$InputData -replace $key,$configurationData.item($key) } $InputData | Out-file $newFilePathInput:
Output:
Hope that helps.
2 Replies
- AndySvintsIron Contributor
Hello Hjb118,
You can achieve needed result with one foreach loop:
$filePath = ".\input.txt" $newFilePath = "output.txt" $configurationData = New-Object System.Collections.Generic.Dictionary"[String,String]" $configurationData.add("<Password>","blah") $configurationData.add("<A>","0") $configurationData.add("<x>","0") $replacementlist = @("<Password>","<A>","<x>") $InputData=Get-Content $filePath foreach($key in $replacementlist){ $InputData=$InputData -replace $key,$configurationData.item($key) } $InputData | Out-file $newFilePathInput:
Output:
Hope that helps.