Renaming files with similar pattern

503 views Asked by At

I have some video files and some subtitle files. There is a common part in the name of each of them, for example *E05*.srt and *E05*.mkv.

I'd like to rename each video file to match its subtitle, without .srt of curse.

Can you think of any script for that?

I guess it should be something like this:

Ls *.mkv | ren -path {$_.fullname} -newname { ls -path { "new folder/*" + $_.basename + "*.srt" } | select name }

I don't know!

That second ls doesn't have any problem, and will give me the subtitle, if I run it alone and without ren.

[I can't think of any better title for this post, I'll be thankful if someone can edit it.]

1

There are 1 answers

1
Ansgar Wiechers On BEST ANSWER

Assuming that all subtitle files begin with the basename of their respective video file something like this should work:

Get-ChildItem '*.mkv' | % {
  $newname = Get-Item ($_.BaseName + '*.srt') | select -First 1 -Expand BaseName
  if ($newname) { Rename-Item $_ "$newname.mkv" }
}

select is an alias for Select-Object, which allows you to select particular properties of the input object(s). That will still leave you with an object, though, just with a specific set of properties (even if it's just one). However, in some situations you'll want just the value of a property instead of an object with that property. That's what the -ExpandProperty parameter (-Expand for short) is for. It expands the given property to its value, in this case the basename string.

Demonstration:

PS C:\> Get-Item .\test.txt

    Directory: C:\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        13.06.2015     22:54        633 test.txt

PS C:\> Get-Item .\test.txt | Select-Object BaseName

BaseName
--------
test

PS C:\> Get-Item .\test.txt | Select-Object -ExpandProperty BaseName
test