2
{"running": 1, "finished": 3, "node_name": "L-2.local", "pending": 0, "status": "ok"}

I'm trying to parse this response to check the value of "running" with a bash script. I know there's libraries to do this, but some reason the jq library wouldn't install, and I prefer not to install it, as I only need it for this one command. Normally I'd use Python instead.

I tried using this command from another answer, on the response

| grep -Po '"running":"\K[^,]*'

but it failed due to the "."

bash: {"running": 0, "finished": 0, "node_name": "L-2: command not found

Is there a way to get it to check the value of "running" with grep, and not have the error?

3
  • 2
    You have a " in the pattern after :, but there is no quote in the string. Use echo '...string...' | grep -Po '"running":\s*\K[^,]+'. If you are sure there are digits only, use '"running":\s*\K\d+' Commented Jul 28, 2017 at 7:18
  • Thanks, I meant to add the version without the quote. I now discovered the -P option doesn't work with OSX, so can't get it to work yet. Commented Jul 28, 2017 at 10:44
  • You may use sed to get the value, though it won't look pretty. See my answer. Commented Jul 28, 2017 at 10:59

2 Answers 2

3

First, this error bash: {"running": 0, "finished": 0, "node_name": "L-2: command not found is because you don't use echo before your expression.

use : echo '{"running": 1, "finished": 3, "node_name": "L-2.local", "pending": 0, "status": "ok"}' | grep -Po '"running":\s*\K\d+'

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

Comments

1

You may use sed to remove what you do not need and only capture and keep what you need using a capturing group and a backreference:

s='{"running": 1, "finished": 3, "node_name": "L-2.local", "pending": 0, "status": "ok"}'
echo $s | sed 's/.*"running":[[:space:]]*\([0-9]*\).*/\1/'

See the online demo.

Pattern details

  • .* - any 0+ chars as many as possible
  • "running": - a literal substring
  • [[:space:]]* - 0+ whitespaces
  • \([0-9]*\) - a capturing group (note the escapes, they are necessary since the pattern is POSIX BRE compliant) matching 0 or more digits
  • .* - the rest of the line.

The \1 is the backreference to the Group 1 value.

Comments

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.