I'm using bash script that needs to read the JSON output and parse a value from different JSON variables or strings. Here's the sample output. It needs to read the value next to the Content or from any other variable. Such as,

Lookup Content and be able to print Value1.

Lookup DeviceType and be able to print Value4

Sample Ouput: {"Content":"Value1","CreationMethod":"Value2","database":"Value3","DeviceType":"Value4"}

I tried the combination of sed and awk sed 's/["]/ /g' | awk '{print $4}', but only if the position of Content remains the same in the output. otherwise in the different JSON output, the positioning of Content changes that puts the value out of scope thus awk '{print $4}' picks up the wrong value.

  • 2
    "No jq" - no good JSON parsing – RomanPerekhrest Nov 8 at 15:55
  • 3
    This would be trivial with jq, or any other JSON parser. With sed and or awk, you would not only have to rely on the document always being formatted exactly the same way, but also do your own string decoding in case the data is JSON encoded. – Kusalananda Nov 8 at 15:56
  • 1
    Is using bash a mandatory requirement? – schaiba Nov 8 at 15:56
  • 1
    Is Perl allowed? – choroba Nov 8 at 16:05
  • 2
    How about Python? Any scripting language? What is the reason for ruling out the most suitable tools for the job? – JigglyNaga Nov 8 at 17:12

Well, if I understand you correctly, with GNU grep and tr:

tr ',' '\n' < foo | grep -Po "(?<=Content\":\").*(?=\")"



With other keyword:

tr ',' '\n' < foo | grep -Po "(?<=database\":\").*(?=\")"

Value 3

Replace the commas for a new line:

tr ',' '\n'

Grep -o only -P perl like regex

grep -Po

Catch the pattern ("<keyword>:"")<value>(") and print only <value>.

  • 1
    Or s="Content"; grep -Po "(?<=$s\":\")[^\"]*" file – bu5hman Nov 8 at 22:02

jqless and perlless sledgehammer using OP's intended sed/awk

s="Content"; sed 's/[{}"]//g' file | awk -v s=$s -F ":" -v RS=',' '($1 == s) {print $2}'

OK, I admit that this is awful...

$ awk 'BEGIN {FPAT="\"[^\"]+\""; RS=","; pat=ARGV[1]; delete ARGV[1]} 
     $1 ~ pat {print $2} '       Content ex.json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.