Search code examples
regexsedgrep

Extracting a part of String using grep/sed


I have a file in linux with similar entries as below

dn: CN=HP_NetworkSupport,OU=groups,DC=HDFCSLDM,DC=COM
dn: CN=Review users,OU=groups,DC=HDFCSLDM,DC=COM

I would like to extract only the CN information, till the first , for ex:

> HP_NetworkSupport
> Review users

in the above case to another file.

What would be command for doing the same.


Solution

  • Using awk

    awk -F"=|," '{print $2}' file
    HP_NetworkSupport
    Review users
    

    or

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

    Set the delimiter to , or =, then print second field.


    To handel field with comma within, you should use a parser for LDAP, but this should work.

    echo file
    dn: CN=HP_NetworkSupport,OU=groups,DC=HDFCSLDM,DC=COM
    dn: CN="Review, users",OU=groups,DC=HDFCSLDM,DC=COM
    
    awk -F"CN=|,OU" '{print $2}' file
    HP_NetworkSupport
    Review, users