【问题标题】:Shell script print some number of words after a specific wordShell 脚本在特定单词之后打印一些单词
【发布时间】:2020-06-29 11:39:13
【问题描述】:

我是 shell 脚本的新手。我有一个日志文件,我只想grep“经过时间”并在此之后打印数字。

日志看起来像这样 -

Thread:MkdirSUProc workarea:92d70a0a8 cid_working_on:3164187 line:1085 clientIP:10.176.118.170:39575 elapsed time:649 ms additional_info:, Replication info:
stack:  fs/server/mapserver/create.cc:1085
        fs/server/mapserver/locks.cc:108 lkOwner:0x92c38c0a8
Thread:WriteFile workarea:9dbc7c538 cid_working_on:2402759 line:875 clientIP:10.176.118.170:0 elapsed time:17287 ms additional_info:, Replication info:  wa = 0x9dbc816c8
stack:  fs/server/mapserver/write/writev3.cc:875

想要输出像 -

649
17287

每当我使用grep 时,它都会打印整行。任何帮助和指导将不胜感激。

【问题讨论】:

  • 试试grep "elapsed time" | cut -d ' ' -f 7 | cut -d ':' -f2

标签: linux bash shell awk command-line


【解决方案1】:

你可以使用:

grep -o 'elapsed time:[0-9]*' file | grep -o '[0-9]*'

或者,如果您的 grep 支持与 Perl 兼容的正则表达式 (PCRE):

grep -Po 'elapsed time:\K[0-9]+' file

【讨论】:

  • 不适用于 BSD 变体,但我想由于问题是用 linux 标记的,因此可以这样做。
  • 奇怪的是,如果模式以括号表达式开头,BSD 不喜欢*。如果您将第二个 grep 更改为 grep -o '[0-9]\+',则第一个有效。
【解决方案2】:

第一个解决方案:这可以在单个 awk 中完成,请尝试关注。

awk 'match($0,/elapsed time:[0-9]+/){print substr($0,RSTART+13,RLENGTH-13)}' Input_file

第二个解决方案:尝试使用字段分隔符:

awk -F'elapsed time:|ms' '$2{print $2}' Input_file

输出如下。

649
17287

【讨论】:

    【解决方案3】:

    通常sed 是这些任务的首选。

    您可以使用:

    sed -n 's/.* elapsed time:\([0-9]*\) ms.*/\1/p' file
    

    649
    17287
    

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2022-01-04
      • 2016-12-06
      • 2021-07-04
      相关资源
      最近更新 更多