Ando
Ando

Reputation: 35

PowerShell - lowercase text between two characters

I have a lot of .txt files where I need to lowercase content in between two characters - after "%" and before ";".

The code below makes all content in the files lowercase and I need it to only do it in all instances between the two characters as mentioned.

$path=".\*.txt"
Get-ChildItem $path -Recurse | foreach{    
    (Get-Content $_.FullName).ToLower() | Out-File $_.FullName
}

Upvotes: 2

Views: 166

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

Here an example using regex replace with a callback function to perform the lowercase:

$path=".\*.txt"
$callback = {  param($match) $match.Groups[1].Value.ToLower() }
$rex = [regex]'(?<=%)(.*)(?=;)'

Get-ChildItem $path -Recurse | ForEach-Object {
        $rex.Replace((Get-Content $_ -raw), $callback) | Out-File $_.FullName
}

Explanation:

The regex uses a positive lookbehind to find the position of % and a lookahead for the position of ; and caputes everything between in a group:

enter image description here

The caputred group gets passed to the callbackfunction which invokes ToLower() on it.

Upvotes: 4

Related Questions