问题
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