Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created November 12, 2010 15:14
Show Gist options
  • Star 52 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save dansimau/674203 to your computer and use it in GitHub Desktop.
Save dansimau/674203 to your computer and use it in GitHub Desktop.
Shell script that reads LDIF data from STDIN and outputs as CSV.
#!/bin/bash
#
# Converts LDIF data to CSV.
# Doesn't handle comments very well. Use -LLL with ldapsearch to remove them.
#
# 2010-03-07
# dsimmons@squiz.co.uk
#
# Show usage if we don't have the right params
if [ "$1" == "" ]; then
echo ""
echo "Usage: cat ldif.txt | $0 <attributes> [...]"
echo "Where <attributes> contains a list of space-separated attributes to include in the CSV. LDIF data is read from stdin."
echo ""
exit 99
fi
ATTRS="$*"
c=0
while read line; do
# Skip LDIF comments
[ "${line:0:1}" == "#" ] && continue;
# If this line is blank then it's the end of this record, and the beginning
# of a new one.
#
if [ "$line" == "" ]; then
output=""
# Output the CSV record
for i in $ATTRS; do
eval data=\$RECORD_${c}_${i}
output=${output}\"${data}\",
unset RECORD_${c}_${i}
done
# Remove trailing ',' and echo the output
output=${output%,}
echo $output
# Increase the counter
c=$(($c+1))
fi
# Separate attribute name/value at the semicolon (LDIF format)
attr=${line%%:*}
value=${line#*: }
# Save all the attributes in variables for now (ie. buffer), because the data
# isn't necessarily in a set order.
#
for i in $ATTRS; do
if [ "$attr" == "$i" ]; then
eval RECORD_${c}_${attr}=\"$value\"
fi
done
done
@a2f0
Copy link

a2f0 commented May 16, 2017

This is great, thank you.

@bradtumy
Copy link

bradtumy commented Sep 5, 2017

Great script! Worked perfectly and was exactly what I needed to convert my ldif export to csv.

@banty105
Copy link

I need the opposite script, please help me!
My requirement is to convert csv data to ldif format/file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment