Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell batch rename with regex? Can't figure out the expression

So I have a group of files with the following file names:

52 39 118 070 13200 5480.txt
83 39 010 392 01000 9970.txt
37 39 880 163 17802 0473.txt

I am trying to rename them to something like:

2012 File Description (52-39-118-070-13200-5480).txt
2012 File Description (83-39-010-392-01000-9970).txt
2012 File Description (37-39-880-163-17802-0473).txt

But, I can't figure out what the corresponding regular expression would be, and how to code it into PowerShell. I see tons of examples to remove spaces or underscores, but nothing to add to a string.

Please note that "2012 File Description" would be constant for all files being renamed. The only thing that I would like to change is have the original file name moved into the parentheses and change the spaces to dashes.

Thank you.

like image 314
toolshed Avatar asked Oct 25 '25 23:10

toolshed


2 Answers

You could do it with a one-liner (piping directly to Rename-Item), but for the sake of simplicity I used the Foreach-Object cmdlet:

Get-ChildItem -Filter *.txt | Foreach-Object{   
   $NewName = '2012 File Description ({0}){1}' -f ($_.BaseName -replace '\s','-'),$_.Extension
   Rename-Item -Path $_.FullName -NewName $NewName 
}
like image 56
Shay Levy Avatar answered Oct 28 '25 16:10

Shay Levy


"52 39 118 070 13200 5480.txt" -replace "(.*)(\.txt)",'2012 File Description ($1)$2'

gives:

2012 File Description (52 39 118 070 13200 5480).txt

Important: the replacement string is using single quotes, because the dollar sign "$" character needs to be escaped if it appears in a string that is quoted with double quotes. Alternatively I could have written:

"52 39 118 070 13200 5480.txt" -replace "(.*)(\.txt)","2012 File Description (`$1)`$2"
like image 41
jon Z Avatar answered Oct 28 '25 16:10

jon Z