# Renaming multiple file extensions based on a condition

Hi I would like to rename a bunch of .bin files into .oma based on one condition: the first 4 bytes of the .bin files are supposed to include the string 'RIFF'. If it includes something else, then do not rename it.

I'm currently using Windows 7 Pro. Is there such automation software already built in that I can use?

I also need this automation to change a bunch of mp3 titles later on...

-
you mean bin file of size 4 bytes should be re-named with a pre-fix RIFF – subanki Sep 10 '10 at 9:42
No... is my description too vague? :/ – FlavorOfLife Sep 10 '10 at 10:13

You can achieve this with the following script for the built-in Windows Powershell:

$files = get-childitem | where {$_.extension -eq '.bin'}

foreach ($f in$files)
{
try
{
$reader =$f.Open([System.IO.FileMode]::Open)
$bytes = new-object byte[] 4$numRead = $reader.Read($bytes, 0, $bytes.Count) } finally { if ($reader)
{
$reader.Dispose() } if ($numRead -eq 4)
{
$encoding = new-object "System.Text.ASCIIEncoding" if ($encoding.GetString($bytes) -eq "RIFF") {$newname = $f.Name.Replace(".bin", ".oma") rename-item$f -newname \$newname
}
}
}
}

-
Kudos Steve, how do I specify the location of my files? I've never used PowerShell before. – FlavorOfLife Sep 11 '10 at 11:50
Steve! I'm nearly there! Please reply so I can tick it as the answer! :) – FlavorOfLife Sep 13 '10 at 23:18
As it stands, the script will just run on files in the directory PowerShell is in. To run on a specific directory, the quickest way to alter the script is to call set-location before any of the above - e.g. "set-location C:\path\to\the\files\" (without the quotes) as first line. – Steve Beedie Sep 14 '10 at 15:23
Cheers Steve, I had a little trouble with execution policies, but after that it all works! (first time PowerShell user) – FlavorOfLife Sep 15 '10 at 5:48

I do not know "out of the box" solution.

Maybe write simple script on python or perl or whatever you like is simplest way.

-
Thanks, I've yet gathered the courage and time to learn a programming language though :) – FlavorOfLife Sep 11 '10 at 11:56

Alright, someone had to post a bash solution.

find . -name '*.bin' -exec head -q -c 4 {} \; -exec printf ' %s' {} \; -exec printf '\n' \;  | grep RIFF | cut -d' ' -f2- | tr "\n" "\0" | xargs -0 rename -v 's/\.bin/\.oma/'