Reputation: 2019
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.
Upvotes: 4
Views: 7099
Reputation: 16616
"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"
Upvotes: 3
Reputation: 126722
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
}
Upvotes: 8
Reputation: 65147
You don't need a regex for this. As Ken says in the comments, you can just use concatenation (which is super easy in Powershell).
Something like:
gci Y:\MyFolder -filter '*.txt' | % {rename-item -path $_.fullname -newname "2012 File Description`($($_.basename)`).txt"
Upvotes: 1