根据条件从顶部命令grep行

时间:2017-11-08 00:36:55

标签: bash unix awk sed grep

[xxxxx@xxxx3 ~]$ top
top - 16:29:00 up 197 days, 19:06, 12 users,  load average: 19.16, 21.08, 21.58
Tasks: 3668 total,  21 running, 3646 sleeping,   0 stopped,   1 zombie
Cpu(s): 14.1%us,  6.8%sy,  0.0%ni, 79.1%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  264389504k total, 53305000k used, 211084504k free,   859908k buffers
Swap: 134217720k total,   194124k used, 134023596k free, 12854016k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 19938 jai_web  20   0 3089m 2.9g 7688 R 100.0  1.1   0:10.26 Engine
 19943 jai_web  20   0 3089m 2.9g 7700 R 100.0  1.1   0:10.14 Engine
 20147 jai_web  20   0  610m 454m 3556 R 78.4  0.2   0:02.54  java
 77169 jai_web  20   0 9414m 1.4g  29m S 21.3  0.6  38:51.69  java
 20160 jai_web  20   0  362m 196m 3336 R 16.7  0.1   0:00.54  java
272287 jai_web  20   0 20.1g 2.0g 5784 S 15.1  0.8 165:39.50  java
 26597 jai_web  20   0 6371m 134m 3444 S  9.6  0.1 429:41.97  java

从上面top命令的片段中我想要grep值为TIME +大于10:00:00且属于' java'过程

所以我期待grep输出如下:

 77169 jai_web  20   0 9414m 1.4g  29m S 21.3  0.6  **38:51.69** java
272287 jai_web  20   0 20.1g 2.0g 5784 S 15.1  0.8 **165:39.58** java
 26597 jai_web  20   0 6371m 134m 3444 S  9.6  0.1 **429:41.97** java

我试过以下:

top -p "$(pgrep -d ',' java)"

但不满足我的条件。请协助

2 个答案:

答案 0 :(得分:1)

我会这样做一次分析。

$ top -n 1 -b | awk '$NF=="java" && $(NF-1) >= "10:00.00"'

答案 1 :(得分:0)

好的,这就是我想出来的......

您需要获取top的输出,仅过滤java行,然后检查每一行以查看TIME是否大于您的限制。这是我做的:

#!/bin/bash
#
tmpfile="/tmp/top.output"

top -o TIME -n 1 | grep java >$tmpfile

# filter each line and keep only the ones where TIME is bigger than a certain value
limit=10
while read line
do
    # take the line and keep only the 11th field, which is the time value
    # In that time value, keep only the first number
    timevalue=$(echo $line | awk '{print $12}' | cut -d':' -f1)

    # compare timevalue to the limit we set
    if [ $timevalue -gt $limit ]
    then
        # output the entire line
        echo $line
    fi
done <$tmpfile

# cleanup
rm -f /tmp/top.output

这里的技巧是提取TIME值,只提取第一个数字。其他数字不重要,只要第一个数字大于10.

有人可能知道通过grep做到这一点的方法,但我对此表示怀疑,我从未在grep中看过条件。