Solved

Linux: Calculating total value of numbers by command

Posted on 2013-11-20
1
233 Views
Last Modified: 2013-11-20
I use the following code to identify the top 3 CPU-hogging processes and return results in JSON format:
# Thanks, simon3270
cat ps.txt | sort | awk '{if (s == $1){n=n+$2}else {if (s != ""){print s " " n};s=$1;n=$2}}END{print s " " n}' | sort -rn -k +2 | awk 'BEGIN{print "{\n \"hogs\": {"}NR <= 3{printf "   \"%s\" %.1f,\n",$1,$2/10}END{print " }\n}\n"}'

Open in new window

(See the attached file, ps.txt)

I want the CPU value of processes to be combined and added togeather by command.  For example:
{
 "hogs": {
   "httpd" 9,
   "ps" 0.7,
   "init" 0.1
 }
}

Open in new window

Also, there should not be a comma after the last item.
ps.txt
0
Comment
Question by:hankknight
1 Comment
 
LVL 14

Accepted Solution

by:
jb1dev earned 500 total points
ID: 39664034
cat ps.txt | sort | awk '{if (s == $1){n=n+$2}else {if (s != ""){print s " " n};s=$1;n=$2}}END{print s " " n}' | sort -rn -k +2 | awk 'BEGIN{print "{\n \"hogs\": {"}NR <= 3{printf "   \"%s\" %.1f",$1,$2; if ( NR != 3 ) { printf ",\n" } else { printf "\n" }  } END{print " }\n}\n"}'

Open in new window

0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Over the last ten+ years I have seen Linux configuration tools come and go. In the early days there was the tried-and-true, all-powerful linuxconf that many thought would remain the one and only Linux configuration tool until the end of times. Well,…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now