Join and process two lines from top command output

只愿长相守 提交于 2019-12-24 16:58:16

问题


I would like to join and process the two lines coming out of the top command:

shell> top -p 1 -b -d 1 | egrep '^top|^Cpu'
top - 15:17:45 up 736 days,  4:32,  3 users,  load average: 0.06, 0.03, 0.00
Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

When trying to use awk and sed commands, I run into trouble - no output is produced. What commands would I use to get the output to look like this:

Time: 15:17:45 Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

Here is a piece of code that could be useful:

shell> echo 'top - 15:17:45 up 736 days,  4:32,  3 users,  load average: 0.06, 0.03, 0.00' | awk -F' up' '/^top/ {print "Time: " $1}' | sed 's/top - //'
Time: 15:17:45

回答1:


try this:

command | sed -n "N;s/top - /Time: /;s/up.*\n//;p" 

At first it reads in the seconds line, then it substitutes "top - " by "Time: ", finally it deletes everything from up unto the first line break.

Output:

Time: 15:17:45 Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

EDIT:

Try this:

top -p 1 -b -d 1 | awk '
    /^top/{a=$0}
    /^Cpu/{
        sub(/top - /,"Time:",a);
        sub(/up.*$/,"",a);
        printf "%s %s\n",a,$0;a=""}'



回答2:


This might work:

top -bn1 |sed -ru '1!d;N;s/^top -\s*(\S*).*\n/Time: \1 /'

The sed -u option apparently load minimal amounts of data from the input files and flushes the output buffers more often. I only have the Busybox version of top so I am guessing it will work.



来源:https://stackoverflow.com/questions/7909695/join-and-process-two-lines-from-top-command-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!