Awk脚本基于匹配正则表达式提取值

时间:2017-06-29 03:24:17

标签: awk grep

我正在尝试编写一个awk脚本,我正在捕获API响应。回复如下所示。

id:0tesss status:ACTIVE created:2016-12-06T13:24:50.000Z activated:2016-12-06T13:26:06.000Z statusChanged:2016-12-06T13:26:06.000Z lastLogin:2017-06-13T06:32:41.000Z lastUpdated:2017-06-13T06:32:58.000Z passwordChanged:null profile:lastName:tack profile:secondEmail:null profile:mobilePhone:null profile:email:karry.t@john.com profile:login:karry.t@john.com profile:firstName:Karry profile:displayName:Karry tack credentials:recovery_question:{question:Who's a ?} 

在上面我只想打印下面的profile:login值。

karry.t@john.com

我怎么打印这个。此响应可能因不同用户而异。所以我必须根据profile.login进行过滤,然后在csv文件旁边打印。感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用此命令(使用trawk)执行此操作:

tr ' ' '\n' | awk -F: '/profile:login/{print $NF}'

样品:

AMD$ echo "id:0tesss status:ACTIVE created:2016-12-06T13:24:50.000Z activated:2016-12-06T13:26:06.000Z statusChanged:2016-12-06T13:26:06.000Z lastLogin:2017-06-13T06:32:41.000Z lastUpdated:2017-06-13T06:32:58.000Z passwordChanged:null profile:lastName:tack profile:secondEmail:null profile:mobilePhone:null profile:email:karry.t@john.com profile:login:karry.t@john.com profile:firstName:Karry profile:displayName:Karry tack credentials:recovery_question:{question:Who's a ?}" | tr ' ' '\n' | awk -F: '/profile:login/{print $NF}'
karry.t@john.com

或仅使用awk

awk -vRS=' ' '/profile:login/{sub(/.*:/, ""); print}'

样品:

AMD$ echo "id:0tesss status:ACTIVE created:2016-12-06T13:24:50.000Z activated:2016-12-06T13:26:06.000Z statusChanged:2016-12-06T13:26:06.000Z lastLogin:2017-06-13T06:32:41.000Z lastUpdated:2017-06-13T06:32:58.000Z passwordChanged:null profile:lastName:tack profile:secondEmail:null profile:mobilePhone:null profile:email:karry.t@john.com profile:login:karry.t@john.com profile:firstName:Karry profile:displayName:Karry tack credentials:recovery_question:{question:Who's a ?}" | awk -vRS=' ' '/profile:login/{sub(/.*:/, ""); print}'
karry.t@john.com

答案 1 :(得分:1)

my $body = { request => $url, nonce => $nonce }; 可以在文件中提取您想要的内容。

awk

简要说明,

  • $ awk '{match($0,/profile:login[^\ ]+/);print substr($0,RSTART+14,RLENGTH-14)}' file karry.t@john.com :找到与match($0,/profile:login[^\ ]+/)中的正则表达式匹配的模式,并将起点存储在$0中,长度为RSTART
  • RLENGTH:打印省略上一个不需要的模式的子字符串