change to the data directly automatically with mig env use
[migration-tools.git] / kmig.d / bin / mig-prepbibs
1 #!/usr/bin/perl
2 # -*- coding: iso-8859-15 -*-
3 ###############################################################################
4 =pod
5
6 =item B<prepbibs> --file foo.mrc 
7
8 Converts a MARC binary file internally to XML and changes 999 subfields to 
9 998s with a special subfield z with a value of 'converted 999 field' added for 
10 identification.
11
12 =back
13 =cut
14
15 ###############################################################################
16
17 use strict;
18 use warnings;
19
20 use Data::Dumper;
21 use Env qw(
22     HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
23     MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
24 );
25 use Pod::Usage;
26 use Switch;
27 use Getopt::Long;
28 use MARC::Batch;
29 use MARC::Record;
30 use MARC::Field;
31 use MARC::Batch;
32 use MARC::File::XML;
33 use Cwd 'abs_path';
34 use Cwd qw(getcwd);
35 use List::MoreUtils qw(uniq);
36 use FindBin;
37 my $mig_bin = "$FindBin::Bin/";
38 use lib "$FindBin::Bin/";
39 use KMig;
40 use open ':encoding(utf8)';
41
42 binmode STDOUT, ":utf8";
43
44 pod2usage(-verbose => 2) if defined $ARGV[0] && $ARGV[0] eq '--help';
45 pod2usage(-verbose => 1) if ! $ARGV[1];
46
47 my $infile;
48 my $i = 0;
49
50 my $ret = GetOptions(
51     'file:s'                     => \$infile
52 );
53
54 my $outfile = $infile . '.prepped_xml';
55 my $errorfile = $infile . '.errors_xml';
56
57 open my $outfh, '>:utf8', $outfile or die "Can't open output file $!\n";
58 open my $errorfh, '>:utf8', $errorfile or die "Can't open error file $!\n";
59
60 my $filetype = `file $infile`;
61 my $batch;
62 if ($filetype =~ m/MARC21/) {
63         $batch = MARC::Batch->new( 'USMARC', $infile );
64 } else {
65         $batch = MARC::Batch->new( 'XML', $infile );
66 }
67 $batch->strict_off();
68
69 while ( eval {$record = $batch->next()} or do { if ($@) { print $errorfh $record->as_xml(); next; } } ) {
70         $i++;
71         print "Processed: $i\n" if ($i % 100) == 0;
72         my @nnn = $record->field('999');
73         foreach my $n (@nnn) {
74                 $n->set_tag('998');
75                 $n->add_subfields( 'z' => 'converted 999 field' );
76         }
77     print $outfh $record->as_xml(),"\n";
78 }
79
80 close ($infile);
81 close ($outfile);
82 close ($errorfile);
83
84 ########### functions
85
86 sub abort {
87     my $msg = shift;
88     print STDERR "$0: $msg", "\n";
89     exit 1;
90 }