How do I use grep to extract a specific field value from lines

后端 未结 2 764
情书的邮戳
情书的邮戳 2020-12-20 23:19

I have lines in a file which look like the following

....... DisplayName=\"john\" ..........

where .... represents variable nu

相关标签:
2条回答
  • 2020-12-20 23:49

    Specifically:

    sed 's/.*DisplayName="\(.*\)".*/\1/' 
    

    Should do, sed semantics is s/subsitutethis/forthis/ where "/" is delimiter. The escaped parentheses in combination with escaped 1 are used to keep the part of the pattern designated by parentheses. This expression keeps everything inside the parentheses after displayname and throws away the rest.

    This can also work without first using grep, if you use:

    sed -n 's/.*DisplayName="\(.*\)".*/\1/p'
    

    The -n option and p flag tells sed to print just the changed lines.

    More in: http://www.grymoire.com/Unix/Sed.html

    0 讨论(0)
  • 2020-12-20 23:53

    This works for me:

    awk -F "=" '/DisplayName/ {print $2}'
    

    which returns "john". To remove the quotes for john use:

    awk -F "=" '/DisplayName/ {gsub("\"","");print $2}'
    
    0 讨论(0)
提交回复
热议问题