Search code examples
regexpowershelltextspecial-characterslowercase

PowerShell - lowercase first word after special character in txt files


I have a lot of .txt files where I need to lowercase every instance of a string/word after the character "%" but not the following words after the first word. I'm trying to do it in PowerShell.

I have this:

%WORD WORD2 WORD3 %WORD4

I need this:

%word WORD2 WORD3 %word4

The code below makes all content in the files lowercase and I need it to only do it in all instances of the first word after the character "%".

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

Solution

  • Sorry Ando, I forgot the answer your question in the comment. This is how the regex should look like: (?s)(?<=%)(\w+).*(?=;)

    enter image description here

    Here the code to lowercase the first word:

    $path=".\*.txt"
    $callback = {  param($match) $match.Groups[1].Value.ToLower() }
    $rex = [regex]'(?s)(?<=%)(\w+).*(?=;)'
    
    Get-ChildItem $path -Recurse | ForEach-Object {
            $rex.Replace((Get-Content $_ -raw), $callback) | Out-File $_.FullName
    }
    

    Note: If you don't need to do that for every word between % an ;, then the regex would be:

    (?<=%)(\w+)