i am writing personal parser for json on bash. So, i need to make grep of line. For example, part of my json-file.
{
"host": "127.0.0.1",
"hhost": "127.0.0.2",
}
Of course, after trying cat json.txt | grep host
cat json.txt | grep host
, i received:
"host": "127.0.0.1",
"hhost": "127.0.0.1",
I found, how to find only host
without hhost
. I used
cat json.txt | grep '"host"'
Everything is good
"host": "127.0.0.1",
But i want to use it in bash script:
#!/bin/bash
#in a future, i want to read variable var from reading from console
var=host
search='"$var"'
echo $search
In a result, i have:
"$var"
What i did wrong ? Can you advice me please ?
You could use jq , to parse the JSON file for this you will need first a proper valid json
{
"host": "127.0.0.1",
"hhost": "127.0.0.2"
}
Then you could just do something like:
#/bin/sh
HOST=$(jq '.host' data.json)
echo $HOST
...
if you put a variable inside single quotes in bash, I does not get evaluated, you should just use:
search="$var"
if you want the variable to be enclosed by quotes, just escape them like this:
search="\"$var\""
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.