0

I'm looking to parse the output of an LDAP query. I want to retrieve a specific OU value within the DN that I am printing

dn: ObjectName=Value,ou=12,ou=Users,dc=example,dc=com

I am retrieving 3 total attributes values, but I only want the ou=[\d]{1,2} to be printed as part of the DN that I am printing. Here is an example of my code that gives the full DN:

<LDAP SEARCH QUERY> | awk -F': ' '/dn: /{dn=$2}/^Attribute1: /{Attribute1=$2}/^Attribute2: /{print dn","Attribute1","$2}'

I'm not sure how to parse the ou=12 in the example. I have tried several different but have not succeeded. I would like to use Awk to do this as this will be ported to several systems and perl/python isn't an option in all cases. I suppose it's like using grep -o but using Awk instead.

Here is the desired output:

12,Attribute1,Attribute2
1

If you use only basic awk you can split the found dn variable value into parts separated by the string ",ou=" (assuming ou= is not first), then either look for a number (or take the second item of the split if you know that is always that field):

n = split(dn,x,",ou=")
for(i=1;i<=n;i++)if(x[i]+0==x[i])v = x[i]
# or just do:  v = x[2]

For your example input, you would get in array x at index 1, 2, and 3, the values:

ObjectName=Value
12
Users,dc=example,dc=com

We test for a number by adding 0 to the string. awk converts the string to a number (0 if it is not a number). If the result is the same as the original string, we have a simple number.

Alternatively, if you have gnu awk you can use gensub to match for the pattern and capture with () the number part, replacing the whole dn value with it:

v = gensub(".*,ou=([0-9]{1,2}),.*","\\1",1,dn)
0

Here's what I ended up doing:

awk -F': ' '/^dn: /{split($2, ou, "," seps)}/^Attribute1/{Attribute1=$2}/^Attribute2/{print ou[2]","$2","Attribute1}'

The "ou=" is still there, but I am able to easily modify my script to accommodate.

ou=12,Attribute1,Attribute2

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.