#!/usr/bin/env perl use strict; use warnings; # Bail out if no file is given as an argument. my $ldap_file = shift || usage(); # To save output with extension .csv. my $csv_file = "$ldap_file.csv"; # Preserve order of header labels. my @header = qw(cn host description env keyWords l sysadm1 sysadm2 administratorContactInfo nsHardwarePlatform version); # Boiler plate to open input and output files handles. open my $in, '<', $ldap_file or die; open my $out, '>', $csv_file or die; # Write the header labels. print $out join (',', @header[0..$#header]), "\n"; # Work engine. { # Record separator is a paragraph representation. local $/="\n\n"; # Process one record at a time. while(my $record = <$in>) { my %data = (); chomp $record; # Remove the record separator. $data{@header} = (); # To label the data. my @entries = split '\n', $record; # Create data entries. # Work with each entry. foreach my $entry (@entries){ if ($entry eq "") { next; } my ($key, $value) = split ":", $entry, 2; # split only by first equal. if ($key eq "" or $key eq "dn") { next; } if ($value eq "") { print "empty value: entry=$entry\n"; } $value =~ s/^\s+//; # Clean leading spaces. $value =~ s/\s+$//; # Clean trailing spaces. if ( exists $data{$key} ) { $data{$key} .= ("," . $value); } else { $data{$key} = $value; } } # Separate entries with commas. foreach my $key (keys %data) { print "key=$key, value=$data($key)\n"; $data($key) =~ s/(^|$)/"/g if $data($key) =~ /,/; } my $row = join ',', (map{ $data{$_}?$data{$_}:""} @header); # Write to output file. print $out "$row\n"; } } # Dismiss file handles. close $in; close $out; # Feed back to user. print "$csv_file has been saved in the current directory\n"; sub usage { print "Usage: $0 ldapfilename\n"; exit 1; }