Extracting a part of String using grep/sed

前端 未结 5 1095
情话喂你
情话喂你 2021-01-18 12:23

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
<         


        
相关标签:
5条回答
  • 2021-01-18 12:25

    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
    
    0 讨论(0)
  • Using sed:

    $ sed -r 's/.*CN=([^,]*),.*/\1/' inputfile
    HP_NetworkSupport
    Review users
    
    0 讨论(0)
  • 2021-01-18 12:45
    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
    >
    
    0 讨论(0)
  • 2021-01-18 12:47

    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
    
    0 讨论(0)
  • 2021-01-18 12:49

    Pipe it through this command:

    sed -E "s/.*CN=(.+?),OU=.*/\\1/g"
    
    0 讨论(0)
提交回复
热议问题