filepowershellreplacerename

Renaming files by reformatting existing filenames - placeholders in replacement strings used with the -replace operator


I have a few video file like this: VideoName_s01e01.mp4 where the season and episodes are variables. I want to add an underscore ("_") between the s?? and e??.

I have been using for renaming purposes, I have a starting point:

GCI $path -filter '*_s??e??*' -rec |  Ren -new { $_.name -replace '_s[0-9][0-9]', '_s[0-9]_[0-9]_' } -passthru    

This actually renamed my files VideoName_s[0-9]_e[0-9].mp4.

Basically, I am looking for the characters s??e?? I just don't know how to make them variables in the replace section.

I think the best method would be:

  1. Find the position of e??s?? (let's call it X).
  2. split the string at X-3.
  3. concatenate the string with a "_" in the middle.

Solution

  • Martin Brandl's answer provides an elegant and effective solution, but it's worth digging deeper:

    PowerShell's -replace operator (... -replace <search>[, <replace>]):


    The "replacement language" for referencing regex captures in a string-typed <replace> operand is itself not a regular expression - no matching happens there, only references to the results of the regex matching are supported, via $-prefixed placeholders that are not to be confused with PowerShell variables.

    For convenience, here are the references supported in the <replace> string (excerpted from the page linked above, with emphasis and annotations added):

    Finally, note that: