Ldap – Multiline data list (ldif file) manipulation with awk or other tool

awkldap

I'm trying to manipulate an ldif file with multiple entries. My purpose is to parse this existing ldif file, extracting the "givenName" and "sn" attributes, so to generate a "mail" attribute. I was thinking about AWK or Sed, but unfortunately I'm not an expert on the two nice tools. An example:

original file

dn: cn=fremer, ou=people, dn=domain, dn=com
cn: fremer
givenName: Freddy
sn: Mercury

dn: cn=markno, ou=people, dn=domain, dn=com
cn: markno
givenName: Mark
sn: Knopfler

Output:

dn: cn=fremer, ou=people, dn=domain, dn=com
mail: freddy.mercury@domain.com

dn: cn=markno, ou=people, dn=domain, dn=com
mail: mark.knopfler@domain.com

The dn is needed since I will take the resulting ldif and pass it to "ldapadd" for LDAP update.
Any suggestion or hint on where should I look at?
Thank you!

Best Answer

You can do this with an awk script

#!/bin/awk -f
/^dn:/ {split($0,dname,", dn=");print $0 }
/^cn:/ { cn = $2 }
/^givenName:/ { gn = tolower($2) }
/sn:/ { sn = tolower($2) ; printf("mail: %s.%s@%s.%s\n\n",gn,sn,dname[2],dname[3] ) }

to use, save the above in a file e.g. awkscript and make it executable then

./awkscript datafile

Given your input this script outputs

dn: cn=fremer, ou=people, dn=domain, dn=com
mail: freddy.mercury@domain.com

dn: cn=markno, ou=people, dn=domain, dn=com
mail: mark.knopfler@domain.com