Donny
Donny

Reputation: 95

Creating a name/email-textfile from the output of ldapsearch

well, I need to generate a single text file with name and emailaddress in the format

name, emailaddress

from the output of ldapsearch. But that is not as simple as it looks like (at least for me).

I am at the point where I have a list of email addresses:

 ldapsearch -x -b ou=<somevalue>,ou=<somevalue>,ou=<somevalue>,dc=<somevalue>,dc=<somevalue> objectClass=posixAccount | grep "^mail: .*$" | awk '{print $2}'

and a list of names:

 ldapsearch -x -b ou=<somevalue>,ou=<somevalue>,ou=<somevalue>,dc=<somevalue>,dc=<somevalue> objectClass=posixAccount | grep "^description: .*$" | awk '{print $2,$3}'

but whatever I tried - I don't get one single command giving me the list I need as shown above ...

This command gives me both name and email - but not in one line:

ldapsearch -x -b ou=<somevalue>,ou=<somevalue>,ou=<somevalue>,dc=<somevalue>,dc=<somevalue> objectClass=posixAccount | awk '/description:|mail:/{print $2,$3}'

Is there a way to make a cool regex to solve this? Or something brilliant shell command I would not think of?

Any help will be highly appreciated.

regards

Dirk

Upvotes: 2

Views: 2452

Answers (2)

glenn jackman
glenn jackman

Reputation: 247012

If I recall, this ldap output records separated by blank lines, so you could write:

perl -00 -ne '
    /(?<=description: )(.*$)/m and print "$1, ";
    /(?<=mail: )(.*$)/m and print "$1\n";
'

Upvotes: 1

Xophmeister
Xophmeister

Reputation: 9219

The problem you have is that the output of ldapsearch spools on to separate lines, so when you grep, you get something like:

description: Joe Bloggs
mail: [email protected]

If you can assume that all your directory entries have a description and mail field and that ldapsearch will consistently output them in this order, then you can pipe the result of grep into sed (here shown on multiple lines for clarity):

ldapsearch ... |
grep -e '^(description|mail):' |
sed -e 'N;s/description: \(.*\)\nmail: \(.*\)/\1, \2/;P;D'

This sed script groups lines into two, then runs a regex substitute (note that this isn't necessarily portable, so you might need to experiment) to remove the field names, prints and deletes its current buffer, so it can move to the next pair. You may be able to produce a magic regex that doesn't care about the order in which fields are returned by ldapsearch, but life's too short!

Upvotes: 2

Related Questions