1

I want to get output of following small shell script in json form.

#!/bin/bash

 top -b -d1 -n1 | grep Cpu 

Output:

Cpu(s):  6.2%us,  1.6%sy,  0.2%ni, 90.9%id,  1.1%wa,  0.0%hi,  0.0%si,  0.0%st

Required Output:

{"Cpu": "6.3" }

How can I convert output of such every shell scripts in json form ?

3
  • what output do you expect? Commented Mar 13, 2013 at 10:16
  • that's it? only "Cpu""6.2%"? I suggest you add an expecting output for that line in your question, so that you could get the right answer to your question. Commented Mar 13, 2013 at 10:34
  • do you want a bash script, say one or two lines? Commented Mar 13, 2013 at 11:00

2 Answers 2

2

You could try this

echo "{\"Cpu\":\"`top -b -d1 -n1 | grep Cpu | cut -f3 -d " " | cut -f1 -d %`\"}"

A brief description: First, take a look at man cut, especially -f and -d arguments. The \"s are simply double quotations, which should be preceded with a backslash to avoid misunderstanding by shell interpreter. And at last, anything enclosed in back quotation marks `` would be executed, as described here.

Sign up to request clarification or add additional context in comments.

2 Comments

valid Json form is {"Cpu": "6.3" }, You are very near to desired output.
The script is updated. I've also added some descriptions so you know what's going on here.
0

try this line:

your commands ...|awk  'BEGIN{FS="\\(s\\):\\s*";OFS="";q="\x22" }{$1=q$1q;sub(/%.*$/,"%",$2);$2=q$2q; print $1,$2}'

test with your data:

kent$  echo "Cpu(s):  6.2%us,  1.6%sy,  0.2%ni, 90.9%id,  1.1%wa,  0.0%hi,  0.0%si,  0.0%st"|awk  'BEGIN{FS="\\(s\\):\\s*";OFS="";q="\x22" }{$1=q$1q;sub(/%.*$/,"%",$2);$2=q$2q; print $1,$2}'
"Cpu""6.2%"

2 Comments

It's very near to output. it gives me "Cpu"" 6.3%"
@K.KPatel the number is dynamic if you run top, it depends on your cpu load.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.