1

This command

ubus -S call system board

gives me this output

{"kernel":"4.14.195","hostname":"OpenWrt","system":"ARMv7 Processor rev 1 (v7l)","model":"Linksys WRT32X","board_name":"linksys,venom","release":{"distribution":"OpenWrt","version":"19.07.4","revision":"r11208-ce6496d796","target":"mvebu/cortexa9","description":"OpenWrt 19.07.4 r11208-ce6496d796"}}

I want to just extract the model and, if there's a space, replace it with an underscore so I end up with

Linksys_WRT32X
thanasisp
  • 5,855
  • 3
  • 14
  • 31
Fr3nZy
  • 65
  • 1
  • 6

3 Answers3

2

Your command output is json, you can extract the value of the "model" field in pure text and use sed to replace any spaces with underscore.

<command> | jq -r '.model' | sed 's/ /_/g'

or using one jq command to select and replace the text value (thanks @Cyrus)

<command> | jq -r '.model | sub(" "; "_")'

If you don't have jq here is an awk for this

awk -v RS=, -F: '$1 ~ /model/{gsub(/\"/,""); gsub(" ","_"); print $2}'

Have in mind, that one awk or sed for this specific output is fine, but if this was for any json, it could break, json is not text, it can be printed in various lines, it can have additional spaces in places etc.

thanasisp
  • 5,855
  • 3
  • 14
  • 31
  • Is it possible to do it if the command jq is not available? – Fr3nZy Sep 27 '20 at 08:24
  • @Fr3nZy: In this case I suggest to use `perl` and its JSON parser. See: https://stackoverflow.com/a/62344545/3776858 – Cyrus Sep 27 '20 at 08:28
  • Looks like it only outputs in JSON format. -S will keep it as a single line. – Fr3nZy Sep 27 '20 at 08:30
  • @Cyrus It's a limited function bash shell. I only have access to sed awk and grep without having to install additional packages. – Fr3nZy Sep 27 '20 at 08:31
  • I got this. It's very messy but gets it done ``ubus -S call system board | awk -F\",\" '{for(i=1;i<=NF;i++) print $i}' | grep 'model' | sed 's/^\(model":"\)*//' | sed 's/ /_/g'``. Can it be condensed? – Fr3nZy Sep 27 '20 at 08:41
  • see also what to do after [answers](https://stackoverflow.com/help/someone-answers) – thanasisp Sep 27 '20 at 08:54
1

There are many ways to do this. Here's another one:

ubus -S call system board | sed 's/.*"model":"\([^"]*\)".*$/\1/' | tr ' ' _
Thomas
  • 17,016
  • 4
  • 46
  • 70
0

I would attempt to answer this using my own version. Since GNU grep has support for Perl regex, we can get the result using:

ubus -S call system board | grep -oP '"model":"\K[^"]+' | tr ' ' _

We attempt to take advantage of the pattern that the JSON key-value pair is of the form "key-name":"<value>" and try to capture the <value> part using grep.

Amit Singh
  • 2,875
  • 14
  • 30