1

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
animuson
  • 53,861
  • 28
  • 137
  • 147
dabest1
  • 2,347
  • 6
  • 25
  • 25

2 Answers2

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=""}'
Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
Chris
  • 2,987
  • 2
  • 20
  • 21
  • Your command did not produce any output initially as well. I learned that the output is written after some amount of buffer is filled. Is there a way to control sed's buffer time or number of lines, so the output is printed more regularly? – dabest1 Oct 26 '11 at 22:53
  • Thanks @Chris. It displays to the screen without the delay with awk command, but when I output to file, and tail it, it still does not output one line at a time. It is not that critical, but still I'm very curious on what is causing the buffering and how to avoid it? – dabest1 Oct 27 '11 at 19:26
0

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.

potong
  • 55,640
  • 6
  • 51
  • 83
  • Thanks @potong. I have tried your suggestion, but the -u option is not helping with the buffering issue. Also I'm not getting the desired output, I'm getting this with your command: `Time: 15:25:20 Tasks: 162 total, 1 running, 161 sleeping, 0 stopped, 0 zombie`. – dabest1 Oct 31 '11 at 22:26