Sending data through a pipeline over time (TOP, SED)

Viewed 65

I'm trying to produce an output with the top 3 processes by CPU usage produced by the top command, over the last 10 seconds. I can see what I want by launching top in interactive modem, the output of this will update every 10 seconds:

top -o +%CPU -d 10

I can send this result to the sed command through a pipeline, which will give me one reading of the result I want:

top -o +%CPU -d 10 | sed -n '11q;7,10p'

After the timespan specified with the -d flag then the command will resolve and exit. How can I specify that I want the command to be run again and a new output to be produced when the timespan is completed?

WHAT DO I EXPECT: usually the interactive mode of the top command updates its value after a certain timespan has passed, similarly I expect the "cutout" to be updated. In other words, I expect several readings to be produced instead of just one.

2 Answers

This might work for you (GNU watch, top & sed):

watch -tn10 "LINES=10 top -wbn1 -o +%CPU | sed '1,6d'"

Watch the composed command every 10 seconds.

The command-line ends due to the 11q used in the sed script: the q command instructs sed to exit.

Moreover, you cannot use line numbers after the |, as top will generate output again and again.

With the top command available on the Ubuntu 20.04 LTS, the number of lines of the output can be specified with LINES environment variables when both -b and -w options are used.

Give a try to this:

LINES=11 top -b -o +%CPU -d 10 -w | sed -n '/^[[:blank:]][[:blank:]]*[P0-9]/ {p}'
Related