3

I tried to convert it to the JSON format by -J flag, but older lscpu versions have no such functionality. The solutions I've found here didn't help me.

I want to put out here the solution I got from member of another community.

2 Answers2

2

About solution from @palmasd1

LANG=C
lscpu | 
sed -r 's/$ //g;s/ [ ]+//g' | 
awk -F ':' 'BEGIN{printf"{\"cpu\":["}{print x"{\""$1"\":\""$2"\"}";x=","}END{printf"]}"}' | 
tr -d '\n'

Explanations:

  • LANG=C: translation deactivation
  • lscpu: the command
  • awk -F ';' ...: use : character as input field separator
   BEGIN {
       printf "{\"cpu\":["
   }
   {
       print x "{\""$1"\":\""$2"\"}"
       x=","
   }
   END {
       printf "]}"
   }
    • BEGIN { ... }: executed before all line treatments
    • { ... }: treatment for each line
      • x variable is used for adding a coma before each line except first where x is empty
      • $1 and $2 contains first and second field values
    • END { ... }: executed after all line treatments
  • tr -d '\n': remove all LINE FEED character (new line under *UNIX* systems)

Personal notes about this script:

  1. It's not really the same format than lscpu -J command
  2. The output format is not protect against JSON special characters (like /, "...) and field value who contains : character
-1
LANG=C

lscpu   |   sed -r 's/$ //g;s/ [ ]+//g'  | 
awk -F ':' 'BEGIN{printf"{\"cpu\":["}{print x"{\""$1"\":\""$2"\"}";x=","}END{printf"]}"}'  | 
tr -d '\n'

Explanation

  1. Output of lscpu is fed to sed which strips out all spaces at the front of a line, and all double spaces are replaced by single spaces.
  2. awk reformats each line into JSON by wrapping the label and the data in double quotes. Also wraps each line in curly braces, and prefixes every line except the first with a comma.
  3. Finally, tr deletes all the new lines, making one single line of output.

This can be "pretty printed" by piping the output to jq

Criggie
  • 2,580