# -
# - csv2ldif.pl
# -
# - This program takes CSV data and maps it to an update LDIF file
# -
# - Pass the name of the input CSV file as the sole argument. The CSV should be
# - in a format where the first row has column headings and the first column
# - should be the DN (with header 'dn'). The output file will be the name of the
# - input file with the .ldif extension appended.
# -
# - Usage: perl csv2ldif.pl input.csv
# -
# -
# -
# - Heavily modified from Novell Cool Solutions: CSV to LDIF Converter
# - http://www.novell.com/coolsolutions/tools/14462.html
# -
# - Chiang Fong Lee <matik@cflee.net>, Nov 9 2007
# - This script now uses the Text::CSV module to handle CSVs properly -
# - original script did own parsing based on quotes and commas and broke when
# - confronted with output from CSVDE.
# -
# - Only remaining similarities with original FixData2.pl is variable names.
# -
my($csvFile, $ldifType, $inputfile, $outfile);
my($linecount, @fieldmap, $column);
# Get a Text::CSV object
my $csv = Text::CSV->new;
# Check for lack of arguments
if (@ARGV == 0) {
print "Usage: perl csv2ldif.pl input.csv\n\n";
print "See the source for more usage info.\n\n";
}
$csvFile = $ARGV[0];
$ldifType = "replace";
# Try to open source file and destination file
$inputfile = new FileHandle($csvFile) ||
die "Can't open the import file!\n";
$outfile = new FileHandle(">$csvFile.ldif") ||
die "Can't create or open the output file!\n";
### REAL WORK BEGINS ###
# Output LDIF version header.
print $outfile "version: 1\n\n";
$linecount = 0;
while(defined($line = <$inputfile>)) {
$linecount++;
# Parse this line and get it into an array.
$csv->parse($line);
@columns = $csv->fields();
# Read the first line of the data file and build the field names from it.
if($linecount == 1) {
$fieldcount = 0;
# Put every header field into the fieldmap array.
foreach $cc (@columns) {
@fieldmap[$fieldcount] = $cc;
$fieldcount++;
}
next;
}
# Now, for all other lines, output it in LDIF format, appropriately tagged
# with the headers from fieldmap
for($k = 0; $k < $fieldcount; $k++) {
if($k == 0) {
# Output DN first
print $outfile "@fieldmap[$k]: ";
print $outfile "@columns[0]\n";
print $outfile "changetype: modify\n";
} else {
if($k > 1) {
# Output separator between attributes
}
# Output change declaration, then new value
print $outfile "$ldifType: @fieldmap[$k]\n";
print $outfile "@fieldmap[$k]: @columns[$k]\n";
}
}
# Cleanup and close last change pair
}