Solved

Linux: skip if no item matches

Posted on 2013-11-20
1
325 Views
Last Modified: 2013-11-21
I use the following code to identify the top 200 CPU-hogging processes and return results in JSON format:
cat ps.txt | grep -v '%CPU' | grep -v '0.0' | 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 "{\"hogs\":{"}NR <= 200{ if(NR != 1) { printf ", " } printf " \"%s\":%.1f",$1,$2; } END{print "}}"}'

Open in new window

(See the attached file, ps.txt)

It works great but if there are no matching results then I want it to return nothing at all.  No JSON should be output unless there is at least one resource with a value greater than 0.
ps.txt
0
Comment
Question by:hankknight
1 Comment
 
LVL 9

Accepted Solution

by:
oheil earned 500 total points
ID: 39665173
This is my proposal:
cat ps.txt | grep -v '%CPU' | grep -v '0.0' | sort | awk 'BEGIN{s="";}{if (s == $1){n=n+$2} else {if (s != ""){print s " " n};s=$1;n=$2}}END{if (s != ""){print s " " n;}}' | sort -rn -k +2 | awk 'BEGIN{p=0;} NR <= 200 {if(s==0&&$1!=""){s=1;print "{\"hogs\":{"} if(s==1){if(NR != 1) { printf ", " } printf " \"%s\":%.1f",$1,$2; }} END{if(s==1)print "}}"}'

Open in new window


I have changed you code slightly. In the first awk, I supressed the empty line which was printed when the input is empty and in the second awk I suppressed all output when no input is coming by adding a status variable s. Therefore I had to move the output in the BEGIN into the middle part of the awk script, because in inside BEGIN you can not check for an empty input.

Oli
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Little introduction about CP: CP is a command on linux that use to copy files and folder from one location to another location. Example usage of CP as follow: cp /myfoder /pathto/destination/folder/ cp abc.tar.gz /pathto/destination/folder/ab…
Introduction We as admins face situation where we need to redirect websites to another. This may be required as a part of an upgrade keeping the old URL but website should be served from new URL. This document would brief you on different ways ca…
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.

757 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

21 Experts available now in Live!

Get 1:1 Help Now