Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a part of String using grep/sed

Tags:

regex

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.

like image 206
bukubapi Avatar asked Oct 08 '13 08:10

bukubapi


4 Answers

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.

Test

$ grep -Po '(?<=CN=)[^,]*' file
HP_NetworkSupport
Review users
like image 163
fedorqui 'SO stop harming' Avatar answered Nov 06 '22 19:11

fedorqui 'SO stop harming'


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
like image 27
Jotne Avatar answered Nov 06 '22 18:11

Jotne


Using sed:

$ sed -r 's/.*CN=([^,]*),.*/\1/' inputfile
HP_NetworkSupport
Review users
like image 33
devnull Avatar answered Nov 06 '22 18:11

devnull


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
>
like image 36
Vijay Avatar answered Nov 06 '22 18:11

Vijay