0

I'm struggling to use a single sed command to extract a number from some json on Linux. Given the following block:

{
    "key1": 100,
    "key2": 200,
}

I'd like the output to be 100 in the above case, but I need to capture it regardless of its length.

So far I've got this:

sed -n '/key1/ s/.*\: //p'
100,

I feel like I should be able to rid myself of the comma without piping out to 'tr' or whatever but I can't seem to manage it.

2
  • 7
    With valid JSON: jq '.key1' file
    – Cyrus
    Aug 15, 2019 at 11:29
  • 7
    JSON/XML/YAML/CSV should all be parsed with a dedicated parser that understands all the corner cases of the markup language. Aug 15, 2019 at 12:23

2 Answers 2

2
$ sed -e '/key1/!d' -e 's/.*\: //' -e 's/,//' testfile 
100
1

Just search for numbers:

$ sed -n '/key1/ s/.*\: \([0-9][0-9]*\).*/\1/p' file
100

or

$ sed -En '/key1/ s/.*\:\s+([0-9]+).*/\1/p' file
100

Personally, I would use grep instead though:

$ grep -oP 'key1":\s*\K\d+' file
100

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.