Regex in Powershell, line by line from txt-file?

Ah, okey. Then I will look on other options. Thank you for all help.

I found a problamatic problem.

look:

$textchange = New-TemporaryFile $wordtochange = New-TemporaryFile

@‘
Anna aSugar
’@ | Set-Content $textchange

@‘
Anna:Annamaria
Sugar:Agave
Android:Phone
’@ | Set-Content $wordtochange

$textchange = Get-Content $textchange -Raw

Get-Content $wordtochange | foreach {
$find,$replace = $_ -split ‘:’
$textchange = $textchange -creplace “$find(?=\W)”,$replace
}

Write-Output $textchange

it gives output:

Annamaria aAgave

should be

Annamaria aSugar

“Sugar” is in the list, not aSugar. My knowlege in regex is a bit limited so I don’t know how to fix this (might be easy) problem.

I know /b /b could be use to match fully words but I don’t manage to get it to work.

It’s \b \b to set the boundary, not /b /b.

That works OK for me:

$textchange = $textchange -creplace "\b$find(?=\W)\b",$replace

One last thing. When using multiple files selected. I get it to work but I can’t manage to understand how to get the script to do the files at all.

 

 

$path = $FileBrowser.FileNames;

If($FileBrowser.FileNames -like “**”) {

foreach($file in Get-ChildItem $path){
Get-ChildItem ($file) |
ForEach-Object {

how do I do the script?

Get-Content $??? | foreach {
$find,$replace = $_ -split ‘:’
$textchange = $textchange -creplace “$find(?=\W)”,$replace
}

}
}

}

 

Just a case of looping over the files in $FileBrowser.FileNames

 

$wordtochange = New-TemporaryFile
@'
Anna:Annamaria
Sugar:Agave
Android:Phone
'@ | Set-Content $wordtochange

Add-Type -AssemblyName System.Windows.Forms
$fileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{Multiselect = $true}
$null = $fileBrowser.ShowDialog()

if ($fileBrowser.FileNames) {

    foreach ($file in $fileBrowser.FileNames) {

        $textchange = Get-Content $file -Raw

        Get-Content $wordtochange | foreach {
            $find,$replace = $_ -split ':'
            $textchange = $textchange -creplace "\b$find(?=\W)\b",$replace
        
        } 

        $textchange | Set-Content $file #Warning: this overwrites the original file.
    
    } 

}

 

Thank you so much. This matches when it’s “word” “word” and “Word” and “Word” butnis it possible to make the dictionary do also match “word:thing” with “Word” and make it “Thing”. Or is the simplest way that I made all words like this in dictionary:

 

word:thing

Word:Thing

 

The simplest solution, I think, is to use the dictionary. It’s not matching that’s the problem but making sure the replacement value has the same case.