Cvs2LDIF

From n0r1sk software solutions
Jump to: navigation, search

Sometimes it is necessary to import adresses book records into Thunderbird. Thunderbird uses the LDIF format as import file.

Normally email clients can at minimum export the existing address book into a CSV formatted file.

To make it easy for Thunderbird (and a friend ask for it) I wrote a simple Perl script that can convert a CSV file to LDIF format.

Here it is: <source lang=perl>

  1. !/usr/bin/perl
  1. Import script CSV to LDIF for Thunderbird
  2. made by Mario Kleinsasser 2012
  1. Define input and output file

$import_file_name=$ARGV[0]; $output_file_name=$ARGV[1];

  1. Open them for read and write
  2. Read uses ISO file encoding with umlauts, write uses utf8

open IMPFILE, "<:encoding(iso-8859-15)", $import_file_name or die $!; open OUTFILE, ">:encoding(utf8)", $output_file_name or die $!;

  1. Dont import first line!

$linecnt=1; $separator="";

while (<IMPFILE>){ if( index($_,";") > 0 ){ $separator=";"; }

if( index($_,",") > 0 ){ $separator=","; }

}

print "Separator found: ".$separator."\n";

  1. Reuse file handle

open IMPFILE, "<", $import_file_name or die $!;

  1. Loop through lines but skip first one

while (<IMPFILE>) { if ($linecnt>1){ convert($_,$separator); } $linecnt++; }

sub convert { # Get the function parameter by reference my ($line, $separator) = @_; # Remove \n chomp($line); # Remove Windows char return $line =~ tr/\015//d; # Split into fields #my @values = split(',', $line); my @values = split($separator, $line);

# Spool out the LDIF print OUTFILE "dn: cn=".$values[1]." ".$values[0].",mail=".$values[2]."\n"; print OUTFILE "objectclass: top"."\n"; print OUTFILE "objectclass: person"."\n"; print OUTFILE "objectclass: organizationalPerson"."\n"; print OUTFILE "objectclass: inetOrgPerson"."\n"; print OUTFILE "objectclass: mozillaAbPersonAlpha"."\n"; print OUTFILE "givenName: ".$values[1]."\n"; print OUTFILE "sn: ".$values[0]."\n"; print OUTFILE "cn: ".$values[1]." ".$values[0]."\n"; print OUTFILE "mail: ".$values[2]."\n"; print OUTFILE "modifytimestamp: 0"."\n"; print OUTFILE "\n"; }


</source>