1.

Solve : Powershell Regular expression to replace part of a file name?

Answer»

Rename FILES using regex in powershell I need a REGULAR EXPRESSION to identify the season and episode. I'm horrible with regular expressions

file name formats:
"something - 01x01a - something.ext" should be "something - S01E01 - something.ext"
"something - 01x01b - something.ext" should be "something - S01E02 - something.ext"
"something - 01x01c - something.ext" should be "something - S01E03 - something.ext"
"something - 01x02a - something.ext" should be "something - S01E04 - something.ext"
"something - 01x02b - something.ext" should be "something - S01E05 - something.ext"
...
"something - 02x01a - something.ext" should be "something - S02E01 - something.ext"
"something - 02x01b - something.ext" should be "something - S02E02 - something.ext"
"something - 02x01c - something.ext" should be "something - S02E03 - something.ext"
"something - 02x02a - something.ext" should be "something - S02E04 - something.ext"
"something - 02x02b - something.ext" should be "something - S02E05 - something.ext"
...
and so on

So I want to keep the part before the "x" (Season) and rename the part after the "x" (Episode), more so increment the value by 1 per season
Using RegEx in any language can be a challenge. I stored your posted data in a file (Media.txt). The output of the script is also a file (Media.final). Best to PUT script and data file in same folder but if not you can tweak the script as needed. Note the continuation character at the end of the first two lines.

Code: [Select]Set-Content -Path .\Media.new -value ((get-content .\Media.txt) `
-replace '^(.*?)( - )(.*)', '$1$2S$3' `
-replace '^(.*?)(x)([0-9]{2})([a-z])(.*)', '$1E$3$5')

$epi = 0
$ssn = 0

Get-Content .\Media.new |
Select-String -pattern '^(?<begin>.*?S)(?<ssn>[0-9]{2})(?<bigE>[a-z])(?<epi>[0-9]{2})(?<end>.*)' |
Select-Object -ExpandProperty Matches |
ForEach-Object {
if ( $_.groups["ssn"].value -NE $ssn ) {
$epi = 0
$ssn = $_.groups["ssn"].value
}
$print = "{0:D2}" -f ($epi += 1)
($_.groups["begin"], $_.groups["ssn"], $_.groups["bigE"], $print, $_.groups["end"]) -join "" |
Out-File -FilePath .\Media.final -Append -Encoding ascii
}

Remove-Item -Path .\Media.new

Good luck.



Discussion

No Comment Found