]> git.donarmstrong.com Git - bin.git/blob - sgf_rename
193a4349117d25d085035b95e808f5897090b8ad
[bin.git] / sgf_rename
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 use IO::File;
6
7 for my $sgf (@ARGV) {
8      my %sgf;
9      my $fh = new IO::File $sgf, 'r'
10           or warn "Unable to open $sgf for reading: $!"
11                and next;
12      while (<$fh>) {
13           chomp;
14           my ($field,$value) = $_ =~ /^([A-Z]{2})\[([^\]]+)\]/;
15           next unless defined $field;
16           if ($field =~ /^[WB]R$/) {
17                $value =~ s/\s+dan/d/;
18                $value =~ s/\s+pro/p/;
19                $value =~ s/\s+kyu/k/;
20           }
21           $sgf{$field} = $value;
22      }
23      undef $fh;
24      my $new_file = join('_',
25                          map {s/\s+/_/g;
26                               s/,//g;
27                               s/[_-]+/_/g;
28                               s/^_//;
29                               s/_$//;
30                               lc($_);
31                          }
32                          map{defined $_?($_):()}
33                          (@sgf{qw(EV RO PB BR)},'v',
34                           @sgf{qw(PW WR DT RE)}
35                          )
36                         ).'.sgf';
37      next if $sgf eq $new_file;
38      warn "$new_file already exists" and next if -e $new_file;
39      rename($sgf,$new_file);
40 }