summaryrefslogtreecommitdiff
path: root/scripts/media/rename-by-libmagic
blob: fe94d50d72079cabedf1d4d60cc382c0640caf22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/perl -w

# add/fix file extensions based on MIME type as detected by libmagic

use File::LibMagic;
use MIME::Types;
$magic = File::LibMagic->new;
$types = MIME::Types->new;

for (@ARGV) {
    open my $fh, "<$_";
    eval {
	$desc = $magic->info_from_handle($fh)->{mime_type};
	@exts = $types->type($desc)->extensions;

	$ext = shift @exts;
	$ext eq "jpeg" and $ext = "jpg";

	$src = $_;
	s/\.[^.]+$//;
	-e "$_.$ext" or rename $src, "$_.$ext";
    };
}