Reputation: 1273
I have json like this:
{"time_stamp":1397718404043,"request_id":"123456"}
I want to extract request_id and put it at the beginning of a line. For example:
123456 {"time_stamp":1397718404043,"request_id":"123456"}
Can I do it with sed or another unix tool? And how?
Upvotes: 1
Views: 112
Reputation: 246807
bash:
json='{"time_stamp":1397718404043,"request_id":"123456"}'
{
[[ $json =~ '"request_id":"'([^\"]+) ]] && echo -n "${BASH_REMATCH[1]} "
echo "$json"
}
123456 {"time_stamp":1397718404043,"request_id":"123456"}
Upvotes: 0
Reputation: 1449
Another solution using perl:
s='{"time_stamp":1397718404043,"request_id":"123456"}'
echo $s | perl -pe 'print /(\d+)"}/ , " "'
123456 {"time_stamp":1397718404043,"request_id":"123456"}
Upvotes: 2
Reputation: 41456
Just a simple extraction:
awk -F\" '{print $(NF-1),$0}'
echo '{"time_stamp":1397718404043,"request_id":"123456"}' | awk -F\" '{print $(NF-1),$0}'
123456 {"time_stamp":1397718404043,"request_id":"123456"}
Or just:
awk -F\" '$0=$(NF-1)OFS$0'
Upvotes: 0
Reputation: 203532
This will produce your posted desired output from your posted sample input:
$ sed 's/\(.*"\([^"]*\)".*\)/\2 \1/' file
123456 {"time_stamp":1397718404043,"request_id":"123456"}
If your actual input doesn't always follow the format you posted, update your question with more information and additional samples.
Upvotes: 4
Reputation: 850
you can use jq
echo '{"time_stamp":1397718404043,"request_id":"123456"}'|./jq ".request_id"
output is:
"123456"
see this page: http://stedolan.github.io/jq/manual/
update:
k='{"time_stamp":1397718404043,"request_id":"123456"}'
printf "%s %s\n" $(echo $k|./jq ".request_id"|tr -d \") $k
Upvotes: 3
Reputation: 785156
Using awk (not a dedicated json parser):
s='{"time_stamp":1397718404043,"request_id":"123456"}'
awk -F '"request_id" *: *"' '{p=$0; sub(/".*$/, "", $2); print $2, p}' <<< "$s"
123456 {"time_stamp":1397718404043,"request_id":"123456"}
Upvotes: 1