b6974c6034cc6ea054a11760d3782f69c376525b
[migration-tools.git] / dbf2tsv
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use XBase;  # or could use DBI and DBD::XBase;
7 use Data::Dumper;
8 use Getopt::Long;
9 use Encode;
10
11 my $in = '';
12 my $out = '';
13 my $help = 0;
14 GetOptions('in=s' => \$in, 'out=s' => \$out, 'help' => \$help);
15
16 if ($help) { &show_help; }
17
18 my @errors; 
19 if ($in eq '') { push @errors, 'Input file must be specified ( --in inputfile.dbf )' };
20 if ($out eq '') { push @errors, 'Output file must be specified ( --out outputfile.tsv )' };
21 if (@errors > 0) { &show_help (@errors); }
22
23 open OUT, ">$out" or die $!;
24
25 my $table = new XBase $in or die XBase->errstr;
26
27 # get list of field names
28 my @names = $table->field_names;
29
30 # dump PATRONID, SURNAME, FIRSTNAME
31 print OUT join ("\t", @names) . "\n";
32
33 sub clean {
34   if ( $_ ) { 
35     s/\\/\\\\/g;
36     s/\n/\\n/g; 
37     s/\r/\\r/g; 
38     s/\t/\\t/g; 
39     Encode::encode("utf8", $_) 
40   } else { ''; } # to avoid 'Use of uninitialized value in join'
41 }
42
43 my $i = 0;
44 for (0 .. $table->last_record) {
45     $i++;
46     my ($deleted, @row) = $table->get_record($_);
47     @row = map (&clean, @row); 
48     print OUT join("\t", @row) . "\n" unless $deleted;
49
50 }
51
52 print STDERR "$i records exported to $out.\n";
53
54
55 sub show_help {
56     my ($msg) = @_;
57     print "\nERROR - $msg\n" if $msg;
58     print <<HELP;
59
60 dbf2tsv - convert XBase DBF to tab-separated format
61
62 Notes:
63
64   * Escapes backslash, newline, carriage return, and tab characters.
65   * Converts to UTF-8.
66
67 Usage: 
68
69   dbf2tsv --in inputfile.dbf --out outputfile.tsv
70
71 HELP
72     exit;
73 }
74
75 =pod
76
77 =head1 NAME
78
79   dbf2tsv - convert XBase DBF to tab-separated values
80
81 =head1 SYNOPSIS
82
83   dbf2tsv --in inputfile.dbf --out outputfile.dbf
84
85 =head1 CAVEATS
86
87   Munges data in the following ways:
88
89   * Escapes backslash, newline, carriage return, and tab characters.
90   * Converts to UTF-8.
91 =cut