Forum Discussion

John_Dodo's avatar
John_Dodo
Brass Contributor
Jul 13, 2022

Rename file using Regex

Hello, 

 

I need to bulk rename files usgin regex. I'm very bad with regex 😕

 

Here is a simplified sample:

...

$source = "blabla"

$target = "blibli"

$files = Get-ChildItem -file -path ".\Desktop\test" -Recurse

..

foreach ($file in $files)
{

if($($file.Name).ToLower().contains($source)){
echo "$($file.Name) contains $source)"}
else{
echo "$($file.Name) does NOT contain $source)"
}

 

Now I want to replace the echo lines with something similar to  :

   $NewName = $_.Name -replace "regex syntax..." #I want to manage the fact that my file could be named blabla.txt but also 4141343blablaffjs.txt
   Rename-Item -Path $_.FullName -NewName $NewName

This is where I need your help.

Thank you.

3 Replies

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    John_Dodo 

     

    Here's an ultra-simple example.

     

     

    Strictly speaking, if you are replacing a contiguous text block, using a string's .Replace() method would be faster but let's not get distracted with that, since working with the file system means you won't realise any performance benefit from going down that path.

     

    Cheers,

    Lain

    • John_Dodo's avatar
      John_Dodo
      Brass Contributor
      Great thank you Lain, then if my understanding is right I don't even need to check if the file name actually contains the $source string, the replace method will simply do nothing if it doesn't find it, am I right?

Resources