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
<
This is one way with lookahead:
grep -Po '(?<=CN=)[^,]*' file > new_file
It gets all text from CN=
(not included) until it finds a comma ,
. The idea of [^,]*
is to fetch any character that is not a comma.
$ grep -Po '(?<=CN=)[^,]*' file
HP_NetworkSupport
Review users
Using sed
:
$ sed -r 's/.*CN=([^,]*),.*/\1/' inputfile
HP_NetworkSupport
Review users
perl -lne 'print $1 if(/CN=([^\,]*),/)' your_file
Tested Below:
> cat temp
dn: CN=HP_NetworkSupport,OU=groups,DC=HDFCSLDM,DC=COM
dn: CN=Review users,OU=groups,DC=HDFCSLDM,DC=COM
> perl -lne 'print $1 if(/CN=([^\,]*),/)' temp
HP_NetworkSupport
Review users
>
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
Pipe it through this command:
sed -E "s/.*CN=(.+?),OU=.*/\\1/g"