1

I have json file with the following structure

{ "tool_first":"1.1.1","tool_second":"2.2.2","tool_three":"3.3.3" }

And I want to retrieve version from it with bash grep. I create something like this

cat myjson.json | grep -Po '"tool_second":\K"[A-Za-z0-9/._]*"'

which give me output

"2.2.2"

How to use variable instead of string "tool_second"? I want to have something like

cat myjson.json | grep -Po '"$x":\K"[A-Za-z0-9/._]*"'

where $x is the variable; x = "tool_second". I can't retrieve information from it with variable. How to escape variable properly in this way? I need just version number, without "".

3
  • 2
    Why parse JSON text with grep?, use a parser that knows the underlying format like jq Commented Apr 19, 2017 at 14:03
  • 2
    I know I can use jq but I want to do it without jq. Commented Apr 19, 2017 at 14:32
  • But why? Compare grep to the jq version: jq --arg x tool_second '.[$x]' myjson.json. Commented Apr 25, 2017 at 13:50

1 Answer 1

2

grep is NOT the right tool for parsing JSON text. Use a more syntax aware tool like jq. Use the answer below only for trivial purposes.

You are not escaping your double-quotes in your string to search present in variable x,

x="\"tool_second\""
grep -Po "$x:\K\"[A-Za-z0-9/._]*\"" file
"2.2.2"

and it can work for other strings too!

x="\"tool_first\""
grep -Po "$x:\K\"[A-Za-z0-9/._]*\"" file
"1.1.1"
Sign up to request clarification or add additional context in comments.

3 Comments

Who/what are you quoting here?
It's not working. In best case it gives me list of all values.
@Tatarinho: It is working fine for me with your input json in question, can you post your actual file you are testing with?

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.