Ajov Crowe
Ajov Crowe

Reputation: 489

Use grep to parse a key from a json file and get the value

Can someone suggest how I can get the value 45 after parsing an example json text as shown below :

....
"test": 12
"job": 45
"task": 11
.....

Please note that I am aware of tools like jq and others but this requires it to be installed.

I am hoping to get this executed using grep, awk or sed command.

Upvotes: 1

Views: 12969

Answers (4)

Ed Morton
Ed Morton

Reputation: 203635

awk -F'[[:space:]]*:[[:space:]]*' '/^[[:space:]]*"job"/{ print $2 }'
sed -n 's/^[[:space:]]*"job"[[:space:]]*:[[:space:]]*//p'

Upvotes: 2

sjsam
sjsam

Reputation: 21965

Use specialized tools like jq for the task :

Had your file looked like

[
{
"test": 12,
"job": 45,
"task": 11
}
]

below stuff would get you home

jq ".[].job" file

Had your file looked like

{
"stuff" :{
.
.
"test": 12,
"job": 45,
"task": 11
.
.
}
}

below

jq ".stuff.job" file

would get you home.

Upvotes: 0

sps
sps

Reputation: 2720

Using awk, if you just want to print it:

awk -F ':[ \t]*' '/^.*"job"/ {print $2}' filename

Above command matches any line that has "job" at the beginning of a line, and then prints the second column of that line. awk option -F is used to set the column separator as : followed by any number of spaces or tabs.

If you want to store this value in bash variable job_val:

job_val=$(awk -F ':[ \t]*' '/^.*"job"/ {print $2}' filename)

Upvotes: 0

anubhava
anubhava

Reputation: 785196

You can use grep -oP (PCRE):

grep -oP '"job"\s*:\s*\K\d+' file

45

\K is used for reseting the previously matched data.

Upvotes: 2

Related Questions