Posted by cflee on Fri 9 Nov 13:10
report abuse | download | new post
- # -
- # - 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.
- # -
- require FileHandle;
- require Text::CSV;
- 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";
- exit;
- }
- $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.
- $linecount = 0;
- $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
- } else {
- if($k > 1) {
- # Output separator between attributes
- }
- # Output change declaration, then new value
- }
- }
- # Cleanup and close last change pair
- }
- close $inputfile;
- close $outputfile;
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.