1

I have this log file which observe user actions on the network, the file contain information from LDAP, very long list like this one:

2015-12-02 10:55:32Z cn=jsmith,ou=sales,dc=company,dc=com
2015-12-02 10:55:54Z cn=bjones,ou=sales,dc=company,dc=com

I want to extract just the cn names :

jsmith
bjones

how can I do it?

4

using sed:

sed -e 's/.*cn=\(.*\),ou.*/\1/' file

using awk

awk -F '[=,]' '{print $2}' file

or

awk -F 'cn=|,' '{print $2}' file
3
% < input
2015-12-02 10:55:32Z cn=jsmith,ou=sales,dc=company,dc=com
2015-12-02 10:55:54Z cn=bjones,ou=sales,dc=company,dc=com
% perl -nle 'print $1 if m/ cn=([^,]+)/' input
jsmith
bjones

on the assumptions that a comma will not appear in the record name (which makes the regular expression fast) and that cn= do not appear elsewhere in the log.

Downsides of this match is that the attribute may be very long or contain characters that cause problems elsewhere. If that is a concern it may be helpful to strictly define limits on what the cn attributes may contain, and then match on that definition, e.g. cn=([a-z][a-z0-9]{1,63}) assuming the attributes can only be lower case, start with a letter, and be 2 to 64 characters long. This may cause problems should attributes longer than 64 characters show up, but on the other hand will not let backticks or globs through that bad code could do unfortunate things with.

2

can be done with sed:

sed 's/^.*cn=\([^,]*\).*$/\1/' file

jsmith
bjones

or grep

grep -oP  '(?<=cn=)[^, ]+' file

or perl

perl -lne '/cn=(\w*),/ && print $1' file

or cut & tr

cut -d'=' -f2 file | tr -d 'ou,'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.